file - Why doesn't "try, except" work with classic "open(fname, 'r')" in python? -


i have function opens file , returns opened file object.

def read_any():     try:         opened = gzip.open(fname, 'r')     except ioerror:         opened = open(fname, 'r')     return opened 

when attempt run function on non-zipped file except condition not triggered , function crashes message: ioerror: not gzipped file.

ok, try , same with statement:

def read_any2():     try:         gzip.open(fname, 'r') f:             return f.read()     except ioerror:         open(fname, 'r') f:             return f.read() 

now, if try run same file function works intended. can explain why doesn't except condition triggered?

to see what's going on, test in repl:

>>> import gzip >>> f = gzip.open('some_nongzipped_file', 'r') 

you see doesn't raise error. once you, however, read object:

>>> f.read() ... (snip) oserror: not gzipped file 

, raises error.

in short: creating file object doesn't read file yet, , doesn't know if should fail or not.

since in first example return file object, when try read later raise exception there (outside raise-except block). in second example return f.read() reads , therefore raises exception. has nothing with block, can see if remove it:

def read_any_mod():     try:         opened = gzip.open(fname, 'r')         return opened.read()     except ioerror:         opened = open(fname, 'r')         return opened.read() 

Comments