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
# "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!")
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 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
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.
with open("notes.txt", "a") as f: f.write("Fourth line\n") with open("notes.txt") as f: print(f.read())
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.
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"])
Alice 28
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?