Python File Handling: Reading, Writing, Binary Modes & Context Managers

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.

Python File Access Modes Comparison Diagram

Figure 37.1: Python file access modes ('r', 'w', 'a', and dual '+' modes) and pointer position behaviors.


1. Writing and Appending Files using the with Statement

Always 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
")

2. Reading Files: 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))

3. Moving the File Pointer: 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

Frequently Asked Questions (FAQ)

How do you read or write non-text binary files (images, audio, PDFs)?

Add a '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()).
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!