11 ms·
You're missing that if an exception gets thrown, the files are still guaranteed to be closed as soon as you exit that 'with' block. Imagine you open 'infile',
by graue 14y ago
You're missing that if an exception gets thrown, the files are still guaranteed to be closed as soon as you exit that 'with' block.
Imagine you open 'infile', but then opening 'outfile' fails. To prevent a resource leak, now you need to close 'infile'. The linked code guarantees this. Likewise if there is any error which aborts the copying, both files will get closed and you don't have to worry so much about corner cases.
See this for more:
http://effbot.org/zone/python-with-statement.htm http://effbot.org/zone/python-with-statement.htm