Home / Topic Library / Python / File Handling
🐍 Python Topic Library

Python File Handling — Read & Write Files Safely

Programs become genuinely useful when they remember things. Files are step one — and Python's with statement makes them nearly impossible to get wrong.

⚡ Quick Answer

Always use the with statement: with open("file.txt") as f: — it closes the file automatically, even if errors happen. Modes: "r" read (default), "w" write (wipes!), "a" append.

§Reading files

reading.py
with open("notes.txt", encoding="utf-8") as f:
    content = f.read()          # whole file as one string
print(content)

with open("notes.txt", encoding="utf-8") as f:
    for line in f:              # memory-friendly line by line
        print(line.strip())     # strip() removes the newline

§Writing & appending

Danger: mode "w" erases the file the instant it opens. Use "a" to add to the end.

writing.py
with open("scores.txt", "w", encoding="utf-8") as f:
    f.write("Ada: 95\n")          # creates or WIPES the file
    f.write("Alan: 88\n")

with open("scores.txt", "a", encoding="utf-8") as f:
    f.write("Grace: 92\n")        # appends — nothing lost

§Why with matters

why_with.py
# without with — easy to leak the file handle:
f = open("data.txt")
data = f.read()
f.close()          # forgotten if an error happens above!

# with — closed automatically, ALWAYS:
with open("data.txt") as f:
    data = f.read()
# file is closed here, even after a crash

§Handling missing files

missing.py
try:
    with open("maybe.txt") as f:
        print(f.read())
except FileNotFoundError:
    print("No file yet — starting fresh.")

from pathlib import Path
if Path("maybe.txt").exists():     # or check first
    print("it's there!")

§JSON — saving real data structures

json_files.py
import json

player = {"name": "Ada", "level": 7, "items": ["sword", "map"]}

with open("save.json", "w", encoding="utf-8") as f:
    json.dump(player, f, indent=2)        # dict → file

with open("save.json", encoding="utf-8") as f:
    loaded = json.load(f)                  # file → dict
print(loaded["items"])                     # ['sword', 'map']

§Common Mistakes to Avoid

🚨 Watch out for these
  • Opening with "w" to read-modify — mode "w" truncates the file immediately — your data is gone before you read it. Read first, or use "a"
  • Forgetting encoding="utf-8" — on Windows the default encoding isn't UTF-8 — emoji and non-English text corrupt without it
  • Hardcoding absolute paths — C:\Users\me\file.txt breaks on every other computer — use relative paths or pathlib

§Frequently Asked Questions

What does the with statement do when opening files?

It guarantees the file is properly closed when the block ends — even if an exception occurs — replacing manual close() calls.

What's the difference between w and a modes?

"w" wipes the file and starts fresh; "a" keeps existing content and adds to the end.

How do I read a file line by line in Python?

Loop directly over the file object: for line in f: — it's memory-efficient even for huge files.

How do I save a dictionary to a file?

Use the json module: json.dump(data, f) to write, json.load(f) to read it back as a dict.

🎓 Want to master Python properly?This reference covers one topic — the full free course takes you from zero to projects, with quizzes and a certificate.
Start the Free Python Course →

§Related Python Topics

← Classes & OOP