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 is Variable Scope in Python? In programming languages, variables need to be defined before using them. These variables can only be accessed in the area where they are defined, this is called scope. You can think of this as a block where you can access variables.
The built-in try function does not create its own scope. Modules, classes, and functions create scope. A complete description of Python scopes and namespaces in the docs.
In the except case text is never assigned. You could set text = None in that block or before the try . This isn't a scope problem.
Solution 1 What you need to do is declare your variable outside of the try scope. Before the try scope so it the variable still exists in your except block. This will raise the exception but x will still have scope (lifetime) and will print out in the 2nd exception case.
What's wrong with the "else" clause ?
for filename in files: try: im = Image.open(os.path.join(dirname,filename)) except IOError, e: print "error opening file :: %s : %s" % (os.path.join(dirname,filename), e) else: print im.size
Now since you're in a loop, you can also use a "continue" statement:
for filename in files: try: im = Image.open(os.path.join(dirname,filename)) except IOError, e: print "error opening file :: %s : %s" % (os.path.join(dirname,filename), e) continue print im.size
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With