📘 Lesson 17 · Intermediate

Python File Handling

Read and write files using open(), with statement, file modes, and CSV handling.

Opening Files — The with Statement

Python's open() opens a file and returns a file object. The mode controls what you can do: "r" = read (default), "w" = write (creates/overwrites), "a" = append, "x" = create new (fails if exists). Always use the with statement — it automatically closes the file when the block ends, even if an error occurs mid-way.

Writing to a File

write.py
# "w" creates the file if it doesn't exist, or overwrites it
with open("notes.txt", "w") as f:
    f.write("First line\n")    # \n = newline
    f.write("Second line\n")
    f.write("Third line\n")
print("Written!")
▶ Output
Written!

Reading a File

read() returns the entire content as a string. Iterating over the file object reads one line at a time — memory-efficient for large files because it never loads everything at once.

read.py
# Read the whole file at once
with open("notes.txt") as f:
    print(f.read())

# Read line by line — efficient for large files
with open("notes.txt") as f:
    for line in f:
        print(line.strip())  # strip removes the \n
▶ Output
First line
Second line
Third line

First line
Second line
Third line

Appending to a File

Mode "a" adds content to the end without erasing existing data. Ideal for log files.

append.py
with open("notes.txt", "a") as f:
    f.write("Fourth line\n")

with open("notes.txt") as f:
    print(f.read())
▶ Output
First line
Second line
Third line
Fourth line

Working with CSV

CSV (Comma-Separated Values) is the most common format for tabular data. Python's built-in csv module handles edge cases like values containing commas automatically.

csv.py
import csv
with open("data.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 28])

with open("data.csv") as f:
    for row in csv.DictReader(f):
        print(row["Name"], row["Age"])
▶ Output
Alice 28
Always use with open(). It's equivalent to manually calling f.close() but guaranteed to run even if your code raises an exception.

🧠 Quick Check

Which mode appends to a file without overwriting?

w
r
a
x

Tags

file handlingopenreadwritewith statementcsvfile modes