Programs that only store data in variables lose all information as soon as the application terminates because RAM memory is volatile. File Handling (File I/O) allows Python to persist data permanently on disk by creating, reading, updating, and deleting files.
Figure 37.1: Python file access modes ('r', 'w', 'a', and dual '+' modes) and pointer position behaviors.
with StatementAlways use the with statement (Context Manager) to prevent file leaks:
# Writing to a new file (mode='w'):
with open("students.txt", "w", encoding="utf-8") as f:
f.write("Roll,Name,Department
")
f.write("101,Rahul Sharma,BCA
")
f.write("102,Pooja Patel,BSc IT
")
# Appending a new record (mode='a'):
with open("students.txt", "a", encoding="utf-8") as f:
f.write("103,Amit Verma,BTech CS
")
read(), readline(), readlines()# 1. Reading line-by-line using file iterator (Memory Efficient!):
with open("students.txt", "r", encoding="utf-8") as f:
for line_number, line in enumerate(f, start=1):
print(f"Line {line_number}: {line.strip()}")
# 2. Reading entire content into a list of lines:
with open("students.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
print("Total lines stored:", len(lines))
tell() and seek()with open("students.txt", "r") as f:
print("Initial position:", f.tell()) # 0
first_line = f.readline()
print("Position after line 1:", f.tell())
# Rewind pointer back to start:
f.seek(0)
print("Position after seek(0):", f.tell()) # 0
'b' to the mode string: 'rb' for reading binary data, and 'wb' for writing binary byte data (e.g. with open('photo.jpg', 'rb') as img: data = img.read()).