Files & the with Statement
Beginneropen() + with reads and writes files with guaranteed closing; iterate file objects line by line for constant-memory processing of files of any size.
Overview
File handling is where beginners leak resources and professionals use with: the context manager closes the file even if an exception fires mid-read. Modes: "r" read, "w" write (truncates!), "a" append, "rb"/"wb" binary; always pass encoding="utf-8" for text. The key habit: a file object is an iterator of lines — loop it directly instead of read()-ing gigabytes into memory.
Reading — Line by Line, Not All at Once
for line in f streams the file with constant memory. read() loads everything (fine for small files), readlines() gives a list. strip() the newline that each line keeps.
# students.txt: one "name,marks" per line
with open("students.txt", encoding="utf-8") as f:
for line in f: # streams — file can be 10 GB
name, marks = line.strip().split(",")
print(name, int(marks))
# file auto-closed here, even on exceptions
# Small files — grab it all
with open("config.txt", encoding="utf-8") as f:
text = f.read()
# Multiple files in one with
with open("in.txt") as src, open("out.txt", "w") as dst:
for line in src:
dst.write(line.upper())
# Without with (what NOT to do):
# f = open("x.txt"); data = f.read(); f.close()
# ^ an exception between open and close leaks the handleWriting & Appending
"w" truncates the file the moment you open it — the classic data-loss mistake; "a" appends. write() does not add newlines; print(file=f) does.
results = {"asha": 91, "ravi": 78}
with open("report.txt", "w", encoding="utf-8") as f: # w TRUNCATES
f.write("Placement Report\n")
for name, score in results.items():
f.write(f"{name}: {score}\n")
with open("report.txt", "a", encoding="utf-8") as f: # append
print("generated by AiCanCode", file=f) # print adds \n
# Exists check before overwriting precious data
from pathlib import Path
if Path("report.txt").exists():
print("careful — already there")
# Binary mode for non-text (images, pickles)
# with open("logo.png", "rb") as f: header = f.read(8)Key Points to Remember
- 1Always with open(...) — guaranteed close on success AND exception
- 2Iterate the file object for constant memory; read() only for small files
- 3Mode "w" truncates at open; "a" appends; add encoding="utf-8" for text
- 4write() adds no newline; print(..., file=f) does
Interview Questions
Sign in to ask AriaWhy is with open() preferred over open()/close()? What guarantees does it give?
How do you process a 10 GB log file in Python without running out of memory?
Ask Aria about Files & the with Statement
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.