[Tutor] if: else: can not get else to work

David david at pythontoo.com
Wed Jul 8 03:36:55 CEST 2009


Hi Tutors,

I have a web cam that saves files in /var/log/motion and it can get 
quite large so I clean it every few days. I came up with this;

#!/usr/bin/python
import commands
import os
from sys import exit

def clean_motion():
     folder = '/var/log/motion'
     if os.path.exists(folder):
         fobj = os.listdir(folder)
         fobj.sort()
         for file in fobj:
             pathname = os.path.join(folder, file)
             if os.path.exists(pathname):
                 print 'removing... ', file
                 os.remove(pathname)
         print folder, 'is clean.'
     else:
         print folder, 'does not exist!'


if __name__ == "__main__":
     if commands.getoutput( "whoami" ) != "root":
         exit("\tYou must be root! Try again please.")
     clean_motion()

My question is I tried to get it to print out when the directory was 
empty like this;

for file in fobj:
     pathname = os.path.join(folder, file)
     if os.path.exists(pathname):
         print 'removing... ', file
         os.remove(pathname)
     else:
         print 'No files to clean'

But if there are no files in the directory it never gets to the else.

-- 
Powered by Gentoo GNU/Linux
http://linuxcrazy.com


More information about the Tutor mailing list