HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

How to correctly close files in Python

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
closecorrectlyhowfilespython

Problem

When working with files in Python, it's quite common to explicitly invoke the close() method after processing the file. This might work fine in a lot of cases, however it's a common pitfall for beginners and developers coming from other languages.
Take for example the following code. If an exception is thrown before calling the close() method, the file would remain open. In such a scenario, the code would stop executing before close() is called, leaving the file open after the program crashes.
One way to mitigate this problem is to encapsulate the write() call in a try statement. This way, you can handle any exceptions and you can use finally to ensure the file gets closed.
Another option offered by Python is to use a with statement which will ensure the file is closed when the code that uses it finishes running. This holds true even if an exception is thrown.

Solution

f = open('filename', 'w')
f.write('Hello world!')
f.close()


One way to mitigate this problem is to encapsulate the write() call in a try statement. This way, you can handle any exceptions and you can use finally to ensure the file gets closed.
Another option offered by Python is to use a with statement which will ensure the file is closed when the code that uses it finishes running. This holds true even if an exception is thrown.

Code Snippets

f = open('filename', 'w')
f.write('Hello world!')
f.close()
f = open('filename', 'w')
try:
  f.write('Hello world!')
finally:
  f.close()
with open('filename', 'w') as f:
  f.write('Hello world!')

Context

From 30-seconds-of-code: file-close

Revisions (0)

No revisions yet.