Ensure File Closed¶
Sourcery refactoring id: ensure-file-closed
¶
Description:¶
Use with
when opening file to ensure closure
Before:¶
file = open("welcome.txt")
data = file.read()
print(data)
file.close()
After:¶
with open("welcome.txt") as file:
data = file.read()
print(data)
Explanation:¶
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.