import Image
import os
for dirname, dirs, files in os.walk("."):
for filename in files:
try:
im = Image.open(os.path.join(dirname,filename))
except IOError:
print "error opening file :: " + os.path.join(dirname,filename)
print im.size
Here I'm trying to print the size of all the files in a directory (and sub). But I know im
is outside the scope when in the line im.size
. But how else do I do it without using else
or finally
blocks.
The following error is shown:
Traceback (most recent call last):
File "batch.py", line 13, in <module>
print im.size
NameError: name 'im' is not defined
What's wrong with the "else" clause ?
Now since you're in a loop, you can also use a "continue" statement:
If you can't open the file as an image, and only want to work on valid images, then include a
continue
statement in your except block which will take you to the next iteration of yourfor
loop.Also, no
;
in Python.