MyInternships.in

Python Files & Errors

Python with Statement

The with statement is the recommended, safer way to work with files in Python. It automatically closes the file for you, even if an error happens partway through.


The Problem with Manual close()

When you call open() and close() manually, an exception raised between them means close() never runs, leaving the file open. You could wrap everything in try/finally, but Python gives you a cleaner built-in tool for this: the with statement.

Risky manual pattern
Python
f = open("data.txt", "r")
content = f.read()   # if this raises an error, close() below never runs
f.close()

What Is a Context Manager?

A context manager is any object that knows how to set itself up and clean itself up automatically, using special __enter__ and __exit__ methods. File objects returned by open() are context managers, so you can hand them to a with statement and Python guarantees close() is called when the block ends — success or failure.

with open() — the recommended pattern
Python
with open("data.txt", "r") as f:
    content = f.read()
    print(content)

# file is automatically closed here, even if an error occurred above
💡

Read this as: "with the file open as f, do the following." As soon as the indented block ends, Python closes f for you.

Writing with a Context Manager

The same pattern works for writing and appending, keeping your code short and safe from forgotten close() calls.

Writing safely
Python
with open("report.txt", "w") as f:
    f.write("Sales Report\n")
    f.write("Total: 4500\n")

Multiple Files at Once

You can open several files in a single with statement, separated by commas — handy for copying data from one file to another.

Two files, one with block
Python
with open("source.txt", "r") as infile, open("copy.txt", "w") as outfile:
    for line in infile:
        outfile.write(line)
  • with guarantees the file is closed, even if an exception is raised inside the block.
  • No need to call close() yourself — this removes an entire class of bugs.
  • It works with any context manager, not just files — locks, database connections, and more.
  • This is considered the Pythonic, professional standard for file handling.
ℹ️

Under the hood, with open(...) as f calls f.__enter__() at the start and f.__exit__() at the end, which is where close() actually happens.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships