› Module 10: File Handling › 10.1 Opening Files and the 'with' Statement
M O D U L E

Module 10: File Handling

Reading from and writing to files on disk, using Python's clean, automatically managed syntax for it.

10.1 Opening Files and the 'with' Statement

open(filename, mode) opens a file and hands back a file object to work with. The common modes are:

  • "r" (read): Opens file for reading (default). Raises FileNotFoundError if missing.
  • "w" (write): Opens file for writing. This overwrites the existing file entirely!
  • "a" (append): Opens file for appending new data to the end without erasing previous content.
  • "b" suffix: Added for binary data (such as images, audio, or PDFs: "rb", "wb").

The Recommended Pattern: The with Statement

The strongly recommended pattern for opening any file is the with statement — a context manager that automatically closes the file the moment the indented block ends, even if an exception is raised somewhere inside it.

This removes the need to ever remember an explicit .close() call, and more importantly, guarantees the file gets closed even when something goes wrong.

The with Statement (from the Guide)

# THE WITH STATEMENT
with open("data.txt", "r") as f:
    contents = f.read()
    print(contents)
# file is automatically closed here, guaranteed
with open(...) as f: File is read/used inside the block f automatically closed on exit
Figure 10.1 — The with statement guarantees the file is closed automatically, even if an error occurs inside the block.

10.2 Reading and Writing Techniques

Python offers several ways to pull data out of an open file, each suited to a different situation:

Reading Techniques

  • f.read() reads the entire file into memory as one single string — fine for small files, risky for huge ones.
  • f.readline() reads just a single line at a time.
  • f.readlines() returns every line as a list of strings.
  • Lazy Streaming (Best Practice): The most memory-efficient technique for large files is iterating directly over the file object itself (for line in f:), which reads the file lazily, one line at a time, rather than loading the whole thing into memory at once.

Writing Techniques

On the writing side, f.write(text) and f.writelines(list_of_strings) send data back out — and it's worth noting that write mode does not add newlines automatically the way print() does, so you must include them yourself.

# Memory-Efficient Reading and Writing
with open("input.txt", "r") as src, open("output.txt", "w") as dst:
    for line in src: # Memory-efficient lazy line streaming
        if line.strip(): # Skip blank lines
            dst.write(line.upper()) # Note: write preserves newline characters in line
MODULE COMPREHENSIVE QUIZ

Module 10 Final Quiz

Test your understanding across all 2 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 10 Final Quiz →
Yukti Mascot