When reading and writing files in python, you’ll often see the use of with:
with open("file_with_data.csv", "r") as infile:
do_things(infile)This is called a Python context manager, and it’s essentially an automatic way to clean up after yourself. The code block above is functionally equivalent to this block:
# This behaves exactly like the example above
infile = open("file_with_data.csv", "r")
try:
do_things(infile)
finally:
infile.close()Without a context manager, we have to remember to manually .close() the file, which is easy to forget especially if you’re busy writing some complicated logic inside the try. If you do forget to .close() your file reference, odds are python’s garbage collection will eventually close it for you, but it’s not guaranteed, and lingering file references can lead to a variety of hard-to-debug issues like:
- Unwritten changes if you’re writing
- Performance slow downs
- Sloppy-looking code (ok this isn’t a technical issue, but I think it counts)
There are more potential problems than just these three, and I’ve put some links with more detail down below, but all file-related issues can be avoided by using a with statement.
Helpful Links
- Why should I close files in Python? – Stack Overflow
- What happens if you don’t close a file in python? – reddit
/r/learnpython - Context Managers – A much deeper dive