I'm old at Perl and new to Python. I know in Perl that fd.close() isn't irrelevant. Writing to a full file system, close() will report the error. Also for socket errors, they appear in close(). So how to do with in Python? Some examples show putting the open() and close() in the same try block which would catch IOError on either. But other examples show close() in the finally block to close the file upon exception. However, what if the exception first occurs in close()?
Does this cover both requirements? (1) Always close the file (2) Catch all IO exceptions?
try: with open(FILE, 'w') as fd: ..... except IOError as err: ..... Thanks, Chris
with open(FILE, 'w') as fdopens a file.open(FILE, 'w')doesn't require the file to already exist, and the question is about failures when closing the opened file, not failure to open the file.with, and (unless the file object's__exit__suppressed the exception intentionally, which it doesn't) would continue to bubble up until caught by theexcept IOErrorblock. Exceptions raised in__exit__would similarly be within thetry, and therefore caught by theexcept.