Skip to content

Ensure File Closed

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: ensure-file-closed

Section titled “Sourcery refactoring id: ensure-file-closed”

Use 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.