File Handling — Types of Files
Python can read and write three broad categories of files:
1. Text Files
Store data as human-readable characters (.txt, .py, .md). Opened in text mode ('t', the default).
with open("notes.txt", "w") as f:
f.write("Python is fun\n")
2. Binary Files
Store data as raw bytes — images, audio, executables (.jpg, .exe, .dat). Opened in binary mode ('b').
with open("image.jpg", "rb") as f:
data = f.read()
print(type(data)) # <class 'bytes'>
3. CSV Files (Comma-Separated Values)
Store tabular data as plain text with commas separating fields — widely used for spreadsheets and datasets.
import csv
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "Course"])
writer.writerow(["Riya", 21, "BCA"])
writer.writerow(["Amit", 22, "BTech"])
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# ['Name', 'Age', 'Course']
# ['Riya', '21', 'BCA']
# ['Amit', '22', 'BTech']
File Open Modes
| Mode | Meaning |
|---|---|
'r' | Read (default) — file must exist |
'w' | Write — creates new / overwrites existing file |
'a' | Append — writes are added at the end |
'x' | Exclusive creation — fails if file already exists |
'r+' | Read and write |
'rb', 'wb', 'ab' | Binary versions of the above |
't' | Text mode (default, usually combined e.g. 'rt') |
Text vs Binary comparison
| Text File | Binary File |
|---|---|
| Human readable | Not human readable |
| Encoded as characters (e.g. UTF-8) | Stored as raw byte sequences |
open(file, 'r') | open(file, 'rb') |
| Slower for very large data | Faster, more compact |
Why use with open(...) as f:
The with statement (a context manager) automatically closes the file even if an error occurs — the recommended pattern over manual open()/close().
# Manual (not recommended -- file may stay open if an error occurs)
f = open("data.txt", "r")
content = f.read()
f.close()
# Recommended
with open("data.txt", "r") as f:
content = f.read()
# file is automatically closed here, even if an exception occurred