Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / Python Tutorial / Chapter 4: Functions, Modules & Files
PYTHON ⏱ 12 min read

File Handling: Reading and Writing Files

Permanent data storage requires saving records to the disk filesystem—whether text notes, CSV spreadsheets, or JSON configs.

What is it?

Python provides native file I/O operations through the built-in `open()` function, supported by the `with` context manager.

Why is it used?

Logging errors, reading configuration files, parsing datasets, and writing user-generated reports.

Detailed Explanation

File Modes: • `'r'`: Read (default). Throws error if file doesn't exist. • `'w'`: Write. Overwrites existing file or creates new file. • `'a'`: Append. Writes to the end of file without overwriting. • `'r+'`: Read and write. The `with` Statement (Context Manager): Always use `with open(...) as f:`! The context manager automatically closes the file stream when the block finishes, even if an unhandled error or exception occurs.

Syntax Structure

Syntax Blueprint
with open('notes.txt', 'w', encoding='utf-8') as f:
    f.write('Content here')

with open('notes.txt', 'r', encoding='utf-8') as f:
    content = f.read()

Code Example

PYTHON Code
# Writing and Reading Course Syllabus Notes
file_path = "student_roster.txt"

# 1. Writing to a file using 'with'
students = ["Rohan Sharma - Python", "Pooja Patil - Excel", "Amit Joshi - Data Analytics"]

with open(file_path, "w", encoding="utf-8") as file:
    file.write("=== IGM Student Roster 2026 ===\n")
    for s in students:
        file.write(f"{s}\n")

print(f"Successfully wrote {len(students)} records to {file_path}.")

# 2. Reading from the file line-by-line
print("\n=== Reading Content Back ===")
with open(file_path, "r", encoding="utf-8") as file:
    for line_num, line in enumerate(file, start=1):
        print(f"{line_num}: {line.strip()}")

Explanation of the Code

• `with open(..., 'w')` creates the file and safely flushes content. • `with open(..., 'r')` reads the file iteratively line-by-line, which is memory-efficient even for gigabyte-sized files. • `.strip()` removes trailing newline characters.

Expected Output

Successfully wrote 3 records to student_roster.txt. === Reading Content Back === 1: === IGM Student Roster 2026 === 2: Rohan Sharma - Python 3: Pooja Patil - Excel 4: Amit Joshi - Data Analytics

Real-World Application

Used across server logs, automated batch CSV processing, and machine learning dataset loaders.

Common Mistakes to Avoid

• Opening files with `f = open(...)` without a `try...finally: f.close()`, causing file lock and resource leak bugs. Always use `with open(...)`! • Forgetting `encoding="utf-8"`, which triggers encoding corruption on non-ASCII characters.

Quick Practice Challenge

Write a snippet that appends a new student to `student_roster.txt` using `'a'` append mode.

Key Takeaways

• Always open files using the `with open(...) as f:` context manager. • Choose correct mode: `'r'` (read), `'w'` (overwrite), `'a'` (append). • Always specify `encoding="utf-8"` for international text safety.