• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Justin Joyce

Practical tips and tutorials about software development.

  • Standing Invitation
  • Featured Posts
  • Latest
  • About

Python Context Managers: the “with” Statement

Posted Dec 19, 2022 โ€” Updated Jan 10, 2024

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:

  1. Unwritten changes if you’re writing
  2. Performance slow downs
  3. 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

Filed Under: Python

Primary Sidebar

Recent Posts

  • Every Built-In Vim Color Scheme (with screenshots)
  • Reverse a string in Python
  • Meeting Cost Calculator
  • Vim find and replace
  • What makes an effective development team

Categories

  • Arrays (5)
  • Command Line (9)
  • Dates (3)
  • Featured (7)
  • Git (7)
  • Golang (5)
  • Javascript (8)
  • Productivity (8)
  • Projects (4)
  • Python (15)
  • Regex (2)
  • Ruby (3)
  • Shell (2)
  • Thoughts (2)
  • Tips (11)
  • Tools (3)
  • Tutorials (1)
  • Vim (4)

Archives

  • July 2024 (1)
  • February 2024 (1)
  • January 2024 (1)
  • December 2023 (1)
  • November 2023 (1)
  • October 2023 (4)
  • September 2023 (1)
  • August 2023 (2)
  • July 2023 (5)
  • June 2023 (3)
  • May 2023 (6)
  • April 2023 (5)
  • March 2023 (5)
  • February 2023 (10)
  • January 2023 (6)
  • December 2022 (7)

Copyright © 2025 ยท Contact me at justin [at] {this domain}

  • Privacy Policy