Introduction & Syntax
File Handling · Study material
Variables disappear when a program ends; files keep data – marks, logs, settings, reports, CSV exports, JSON from an API. Python makes file work short: open() a file in the right mode, read or write it, and let the with statement close it. Tests and interviews ask about the modes ("w" erases, "a" appends, "x" refuses to overwrite), the difference between read(), readline() and readlines(), newlines, seek(), encodings and binary files. This topic covers all of it with programs that really create and read files, then gives you 50 practice questions run on Python 3.
On this page
- open(), file modes and the with statement
- Reading: read, readline, readlines, iteration
- Writing: write, writelines, print(file=)
- File position: tell and seek
- Encodings and binary files
- pathlib, csv and json
Each example starts with os.chdir(tempfile.mkdtemp()), which moves into a new, empty temporary folder, so the files it creates cannot clash with anything on your computer. In your own programs you can leave that line out.
Opening, writing, reading and closing
open(path, mode, encoding=...) returns a file object. Always use it in a with block: the file is closed automatically when the block ends, even if an exception occurs. Pass encoding="utf-8" for text so the program behaves the same on every operating system.
import os, tempfile
os.chdir(tempfile.mkdtemp()) # work in an empty temporary folder
with open("notes.txt", "w", encoding="utf-8") as f: # "w": create or overwrite
f.write("Python file handling\n")
f.write("Line two\n")
# leaving the with block closes the file, even if an error happens
with open("notes.txt", encoding="utf-8") as f: # default mode "r": read text
content = f.read()
print(repr(content))
print(content.splitlines())
print(f.closed)
'Python file handling\nLine two\n' ['Python file handling', 'Line two'] True
File modes
| Mode | Meaning | If the file exists | If it does not |
|---|---|---|---|
"r" | read (default) | reads from the start | FileNotFoundError |
"w" | write | erases it | creates it |
"a" | append | writes at the end | creates it |
"x" | exclusive create | FileExistsError | creates it |
"r+" | read and write | keeps the content | FileNotFoundError |
"b" (e.g. "rb", "wb") | binary: bytes instead of str | combine with r, w, a or x | |
import os, tempfile
os.chdir(tempfile.mkdtemp())
with open("log.txt", "w") as f: # w: truncates (empties) the file first
f.write("first\n")
with open("log.txt", "w") as f:
f.write("second\n") # "first" is gone
with open("log.txt", "a") as f: # a: appends to the end
f.write("third\n")
with open("log.txt") as f:
print(f.read().split())
try:
open("log.txt", "x") # x: create, but fail if the file exists
except FileExistsError:
print("FileExistsError: log.txt already exists")
['second', 'third'] FileExistsError: log.txt already exists
Reading a file
read() returns the whole file as one string (or read(n), n characters); readline() returns the next line including its \n; readlines() returns a list of the remaining lines. The best way to process a large file is to iterate over the file object: it yields one line at a time without loading everything. Use rstrip("\n") or strip() to remove line endings.
import os, tempfile
os.chdir(tempfile.mkdtemp())
with open("cities.txt", "w") as f:
f.write("Pune\nDelhi\nKochi\nLeh\n")
with open("cities.txt") as f:
print(repr(f.readline())) # one line, WITH its newline
print(f.readlines()) # the remaining lines as a list
with open("cities.txt") as f:
for no, line in enumerate(f, 1): # iterating: one line at a time, memory-friendly
print(no, line.rstrip("\n"))
'Pune\n' ['Delhi\n', 'Kochi\n', 'Leh\n'] 1 Pune 2 Delhi 3 Kochi 4 Leh
Writing a file
write(s) writes a string and returns how many characters it wrote – it does not add a newline. writelines(list) writes each string as it is, also without newlines. print(..., file=f) is convenient because it adds spaces and the newline for you. Only strings can be written to a text file: convert numbers with str() or an f-string.
import os, tempfile
os.chdir(tempfile.mkdtemp())
marks = {"Asha": 91, "Ravi": 78}
with open("report.txt", "w") as f:
n = f.write("REPORT\n") # write returns the number of characters
f.writelines(["a", "b", "c\n"]) # writelines adds NO newlines
for name, m in marks.items():
print(name, m, sep=",", file=f) # print can write to a file
with open("report.txt") as f:
print(n)
print(f.read(), end="")
7 REPORT abc Asha,91 Ravi,78
The file position: tell and seek
A file object remembers a position. Reading moves it forward; tell() reports it and seek(n) moves it. After reading to the end, further reads return an empty string until you seek(0). "r+" opens a file for reading and writing without truncating it; writing overwrites characters at the current position.
import os, tempfile
os.chdir(tempfile.mkdtemp())
with open("data.txt", "w") as f:
f.write("abcdefghij")
with open("data.txt") as f:
print(f.read(3), f.tell()) # read 3 characters; position is now 3
f.seek(7) # jump to position 7
print(f.read())
print(repr(f.read())) # at the end: read() returns ""
f.seek(0) # back to the start
print(f.read(2))
with open("data.txt", "r+") as f: # r+: read and write, no truncation
f.write("XY") # overwrites the first two characters
with open("data.txt") as f:
print(f.read())
abc 3 hij '' ab XYcdefghij
Encodings and binary files
Text files are stored as bytes; the encoding (almost always UTF-8) maps characters to bytes. Characters such as é and ₹ take several bytes, so the size on disk can be larger than len(text). Binary mode ("rb", "wb") reads and writes bytes objects with no decoding – for images, PDFs, ZIP files and any non-text data.
import os, tempfile
os.chdir(tempfile.mkdtemp())
text = "Café ₹500"
with open("price.txt", "w", encoding="utf-8") as f:
f.write(text)
print(len(text), os.path.getsize("price.txt")) # characters vs bytes on disk
with open("price.txt", "rb") as f: # b: bytes, no decoding
raw = f.read()
print(raw)
print(raw.decode("utf-8") == text)
with open("pixels.bin", "wb") as f:
f.write(bytes([255, 0, 128, 10]))
with open("pixels.bin", "rb") as f:
print(list(f.read()))
9 12 b'Caf\xc3\xa9 \xe2\x82\xb9500' True [255, 0, 128, 10]
pathlib: modern path handling
pathlib.Path represents paths as objects: join them with /, create folders with mkdir(parents=True, exist_ok=True), find files with glob(), check them with exists() and is_file(), and read or write small files in one call with read_text() and write_text().
import os, tempfile
from pathlib import Path
os.chdir(tempfile.mkdtemp())
folder = Path("reports") / "2026"
folder.mkdir(parents=True, exist_ok=True) # create nested folders
(folder / "jan.txt").write_text("120\n") # write_text / read_text: open + write + close
(folder / "feb.txt").write_text("95\n")
(folder / "notes.md").write_text("draft")
print(sorted(p.name for p in folder.glob("*.txt")))
print(sum(int(p.read_text()) for p in folder.glob("*.txt")))
p = folder / "jan.txt"
print(p.exists(), p.is_file(), p.suffix, p.stem, Path("missing.txt").exists())
['feb.txt', 'jan.txt'] 215 True True .txt jan False
CSV and JSON files
The csv module handles commas, quotes and line endings correctly – open CSV files with newline="". DictReader and DictWriter work with dicts; all values read from CSV are strings. The json module saves and loads lists and dicts with json.dump() and json.load().
import csv, json, os, tempfile
os.chdir(tempfile.mkdtemp())
rows = [{"name": "Asha", "marks": 91}, {"name": "Ravi", "marks": 78}]
with open("marks.csv", "w", newline="") as f: # newline="" is required by csv
writer = csv.DictWriter(f, fieldnames=["name", "marks"])
writer.writeheader()
writer.writerows(rows)
with open("marks.csv", newline="") as f:
for row in csv.DictReader(f): # each row is a dict of STRINGS
print(row["name"], int(row["marks"]) + 5)
with open("marks.json", "w") as f:
json.dump(rows, f, indent=2)
with open("marks.json") as f:
loaded = json.load(f)
print(loaded == rows, loaded[1])
Asha 96
Ravi 83
True {'name': 'Ravi', 'marks': 78}Common mistakes
- Opening a log with "w" – every run erases it; use "a".
- Forgetting \n in write() – lines run together.
- Comparing lines without strip() – "admin\n" != "admin".
- Reading twice without seek(0) – the second read is empty.
- Writing numbers – f.write(42) is a TypeError.
- Using a file after the with block – ValueError: I/O operation on closed file.
- Writing str to a binary file – TypeError: a bytes-like object is required.
Key points to remember
- Use with open(...) as f: – the file closes automatically.
- "w" truncates, "a" appends, "x" fails if the file exists.
- Iterate over a file to process it line by line.
- write() and writelines() never add newlines; print(file=f) does.
- Lines keep their "\n" – strip it before comparing.
- Specify encoding="utf-8" for text files.
- Binary mode reads and writes bytes.
Frequently asked questions
Why use with instead of f.close()?
with closes the file even when an exception occurs halfway through, and you cannot forget the close() call.
How do I read a very large file?
Iterate over it line by line (for line in f:) or read fixed-size chunks with f.read(65536) in a loop; avoid read() and readlines() on huge files.
What is the difference between "r+" and "w+"?
Both allow reading and writing, but "w+" erases the file first (and creates it if needed), while "r+" keeps the content and requires the file to exist.
Where can I learn more?
Read Python File Handling and Python JSON and CSV in the Python tutorial, then practise with the exercises below.