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

David david at pythontoo.com
Wed Jul 8 04:05:13 CEST 2009


Luke Paireepinart wrote:
> 
> 
> On Tue, Jul 7, 2009 at 8:36 PM, David <david at pythontoo.com 
> <mailto:david at pythontoo.com>> wrote:
> 
>     Hi Tutors,
> 
> Hiya david.  Cool e-mail address :) 

Thanks, want luke at pythontoo.com I have a few to spare :)

> 
>     But if there are no files in the directory it never gets to the else.
> 
> Right, if there are no files in the directory, then fobj will contain 0 
> items, so when the outer "for file in obj" loop iterates over it, there 
> will be no values for "file" to take.
> 
> One note - "file" is a builtin (probably deprecated in 3.0 but it's 
> still a builtin in 2.4) so you might not want to use it as filenames. 
>  Maybe use "fname"?  I think in later versions of Python file() is just 
> aliased to open(), or at least it has fewer features, so probably it 
> should be deprecated by now anyway.  Just a thought.
> 
> Do you need help with adding this "no files" statement or would you like 
> to solve it yourself?  I feel like your question was just to confirm 
> that there was nothing wrong with your code, and there isn't, you just 
> need to find the correct way to display this prompt.  hint: if the "for" 
> loop isn't iterating over the items, you won't get to print this 
> message, but you also know that the length of the fobj file must be 0 
> items, right?  Think of how you can use this to your advantage. :)
> 
> 

Ok, here is what I came up with;

#!/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)
         if len(fobj) == 0:
             print 'No files to clean.'
         else:
             fobj.sort()
             for fname in fobj:
                 pathname = os.path.join(folder, fname)
                 if os.path.exists(pathname):
                     print 'removing... ', fname
                     os.remove(pathname)

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


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


More information about the Tutor mailing list