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

Luke Paireepinart rabidpoobear at gmail.com
Wed Jul 8 03:47:23 CEST 2009


On Tue, Jul 7, 2009 at 8:36 PM, David <david at pythontoo.com> wrote:

> Hi Tutors,

Hiya david.  Cool e-mail address :)

> 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.
>
> 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. :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090707/c67244b6/attachment.htm>


More information about the Tutor mailing list