File Handling
with open("notes.txt", "w") as f:Mode 'w' creates the file, or empties it if it already exists.
1Level 1 · BasicsBasics
Variables disappear when a program ends. To keep data, such as scores, notes or settings, programs save it in files. Python makes reading and writing files short and safe.
Opening a file with with
with open("notes.txt", "w") as f:
f.write("Hello file!\n")
open() takes the file name and a mode. The with block automatically closes the file at the end, even if an error happens. Always use with.
| Mode | Meaning |
|---|---|
"r" | read (the default); the file must exist |
"w" | write; erases the file first, or creates it |
"a" | append; adds to the end of the file |
Writing
f.write(text) writes text exactly as given. It does not add a new line, so include "\n" yourself. Only strings can be written, so convert numbers with str() or an f-string.
Reading
with open("notes.txt") as f:
text = f.read() # the whole file as one string
with open("notes.txt") as f:
for line in f: # one line at a time
print(line.strip()) # strip() removes the "\n"
f.readlines() gives a list of lines. Looping line by line is the most memory-friendly way to read big files.
CSV files
CSV (comma-separated values) is the simplest spreadsheet format. The csv module reads and writes it safely, including values that contain commas. Later, pandas reads a CSV into a table in one line.
Files that may not exist
Opening a missing file for reading raises FileNotFoundError. Catch it with try/except, or check first with os.path.exists("data.txt").
Key points: use with open(name, mode) as f:; "w" overwrites, "a" appends, "r" reads; write strings and add "\n" yourself; loop over the file to read lines; use the csv module for CSV data.See it in actionWriting, then reading a file
The first with block writes two lines; the second reads them back as a list.
Try it yourselfExample 1: Write, then read back
The examples run in your browser, so these files live in a small temporary file system there.
Output appears hereWrite then read
Fill the blanks so the program writes Hello file to notes.txt and reads it back.
with open("notes.txt", "") as f: f.write("Hello file") with open("notes.txt", "") as f: print(f.read())
Writing to a read-only file
This should save Score: 90 and print it back, but it crashes. Fix the first open.
Example 2: Append and read line by line
Mode "a" adds to the end instead of erasing.
Output appears hereCount the lines
Fill the blanks so the program appends a line and then counts the lines: 3.
with open("log.txt", "w") as f: f.write("one\ntwo\n") with open("log.txt", "") as f: f.write("three\n") with open("log.txt") as f: print(len(f.()))
Example 3: CSV with the csv module
csv.writer writes rows; csv.DictReader reads each row as a dictionary.
Output appears hereTotal from a file
The starter writes prices to prices.txt, one per line. Read the file and print the total: Total: 75.
Example 4: Handling a missing file
Catch FileNotFoundError instead of crashing.
Output appears hereA file that isn't there
Try to open missing.txt. If it doesn't exist, print No such file instead of crashing.
2Level 2 · IntermediateCSV with headers, JSON and paths
csv.DictReader and DictWriter
With a header row, csv.DictReader gives each row as a dictionary (row["marks"]) so you don't need to remember column numbers. Always open CSV files with newline="".
JSON files
json.dump(data, f, indent=2) saves lists and dictionaries as readable text; json.load(f) reads them back. Perfect for saving a game or settings.
pathlib
Path("data") / "marks.csv" builds paths that work on every operating system. p.exists(), p.read_text(), p.write_text() and Path(".").glob("*.csv") cover most needs.
Encodings
Pass encoding="utf-8" when reading or writing text, especially Bangla, so the file reads the same on every computer.
Example 5: DictWriter, then DictReader
Columns are accessed by name, so their order in the file doesn't matter.
Output appears hereExample 6: Save and load with JSON and pathlib
Run it twice in your head - the second load sees the saved high score.
Output appears here3Level 3 · AdvancedBig files, safe writes and binary data
Stream, don't slurp
f.read() loads the whole file into memory. For big files, loop for line in f:, which reads one line at a time, or read fixed-size chunks with f.read(4096).
Safe writes
If a program crashes halfway through writing, the file is left broken. Write to a temporary file first, then os.replace(tmp, real) swaps it in one step.
Binary mode
"rb" and "wb" work with bytes (images, zip files). f.seek() and f.tell() move around inside a file.
Files in memory
io.StringIO behaves like a text file without touching the disk, which is handy for tests and for reading CSV text you already have.
Example 7: Streaming a large log file
Only one line is in memory at a time, however big the file is.
Output appears hereExample 8: Safe save, binary bytes and StringIO
os.replace swaps the finished file in one step.
Output appears here"w" erases the file the moment it's opened, even before you write anything. To add to an existing file, use "a".What does this print?
with open("t.txt", "w") as f:
f.write("ab")
f.write("cd")
with open("t.txt") as f:
print(f.read())50 graded problems are waiting in Topic Practice.