File Handling
Reading and writing files safely with open() and the with statement.
open(path, mode) gives you a file object; the mode controls what you can do with it:
| Mode | Meaning |
|---|---|
"r" | Read (default) — errors if the file doesn't exist |
"w" | Write — creates the file, overwrites it if it exists |
"a" | Append — creates the file if missing, adds to the end otherwise |
"r+" | Read and write |
Always use with
The with statement guarantees the file is closed automatically, even if an error happens inside the block — this is the standard, correct way to work with files in Python.
with open("notes.txt", "w") as f:
f.write("Subscribe to CodeWithMunnaX!\n")
f.write("Learn Python one topic at a time.\n")
with open("notes.txt", "r") as f:
content = f.read()
print(content)
Without with, you'd need to manually call f.close() — and forgetting it (especially if an exception is raised first) can leak file handles or leave writes unflushed.
Reading line by line
with open("notes.txt", "r") as f:
for line in f: # a file object is iterable, line by line
print(line.strip()) # strip() removes the trailing '\n'
with open("notes.txt", "r") as f:
lines = f.readlines() # or grab them all as a list
print(lines)
Appending instead of overwriting
with open("notes.txt", "a") as f:
f.write("New line added without erasing the old ones.\n")
Working with JSON files
Config files, API responses, and structured data are usually stored as JSON — the json module converts between it and Python dicts/lists directly.
import json
channel = {"name": "CodeWithMunnaX", "subscribers": 250_000}
with open("channel.json", "w") as f:
json.dump(channel, f)
with open("channel.json", "r") as f:
loaded = json.load(f)
print(loaded["name"])- •Always open files with the with statement — it closes the file automatically, even if an error occurs.
- •'w' mode overwrites an existing file entirely; 'a' mode appends without erasing what's already there.
- •A file object is directly iterable — for line in f: reads one line at a time without loading the whole file into memory.
- •json.dump(obj, f) writes a Python object as JSON to a file; json.load(f) reads it back into a dict/list.
Writing, reading, and appending to a file
Saving and loading a dict as JSON
Revision Flashcards
Tap a card to flip it and see the answer.