DEV Community

Cover image for How to correctly close files in Python
Isabelle M.
Isabelle M.

Posted on • Originally published at 30secondsofcode.org

3 2

How to correctly close files in Python

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.

f = open('filename', 'w')
f.write('Hello world!')
f.close()
Enter fullscreen mode Exit fullscreen mode

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.

f = open('filename', 'w')
try:
  f.write('Hello world!')
finally:
  f.close()
Enter fullscreen mode Exit fullscreen mode

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.

with open('filename', 'w') as f:
  f.write('Hello world!')
Enter fullscreen mode Exit fullscreen mode

Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨‍💻

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay