Skip to main content
Albero Academy

Reading & Writing Files

Open, read and write text files safely with the with statement.

File Handling11 min

Programs need to read and write files — configs, data, logs, reports. Python does this with open(), and the golden rule is to wrap it in a with block so the file is closed automatically, even if an error occurs partway through.

The with statement

reading and writing
# Write (creates or overwrites)
with open("notes.txt", "w") as f:
f.write("first line\n")
f.write("second line\n")
# Read the whole file
with open("notes.txt") as f:
text = f.read()
# Iterate line by line — memory-efficient for big files
with open("notes.txt") as f:
for line in f:
print(line.strip()) # strip the trailing newline

File modes

ModeMeaning
"r"Read (default) — errors if the file is missing
"w"Write — creates or OVERWRITES
"a"Append — adds to the end
"x"Create — errors if it already exists
"rb" / "wb"Binary read/write (images, pickles)

A note on paths

For anything beyond a quick script, use pathlib for clean, cross-platform paths:

pathlib
from pathlib import Path
p = Path("data") / "notes.txt" # OS-correct path joining
p.read_text() # shortcut to read
p.write_text("hello") # shortcut to write
p.exists() # True/False

Key takeaways

  1. 01open(path, mode) opens a file; a with block closes it automatically.
  2. 02Modes: r read, w overwrite, a append, x create, add b for binary.
  3. 03"w" overwrites silently — use "a" to append without data loss.
  4. 04Iterate line by line for large files; .read() loads it all at once.
  5. 05Use pathlib.Path for clean, cross-platform path handling.

Finished this chapter?

Mark it complete to track your progress through Python.