Ensure File Closed¶
Sourcery refactoring id:
with when opening file to ensure closure
file = open("welcome.txt") data = file.read() print(data) file.close()
with open("welcome.txt") as file: data = file.read() print(data)
Opening files in this way is more concise, and also ensures that the call to
file.close() is not skipped if there is an exception.
It makes use of Python's
with context manager - under the hood the changed
code behaves like this:
file = open("welcome.txt") try: data = file.read() print(data) finally: file.close()
The file is closed for you as soon as the block is exited, even where an exception has been thrown.