Python Full Tutorial — Part 8: File Handling

By Suraj Ahir December 29, 2025 6 min read

Python — Python OOP
Python — Python OOP
← Part 7 Python Tutorial · Part 8 of 12 Part 9 →

Programs that cannot save data are useless in the real world. File handling is how Python reads from and writes to files — logs, CSVs, JSON configs, text data. This is a practical skill you will use in nearly every real project.

Opening Files — The Basics

File Open Modes
# r  — Read (default). Error if file does not exist.
# w  — Write. Creates file. Overwrites if exists.
# a  — Append. Creates file. Adds to end if exists.
# x  — Create. Error if file already exists.
# rb — Read binary (for images, PDFs, etc.)

file = open("notes.txt", "r")
content = file.read()
file.close()
print(content)

The with Statement — Always Use This

The with statement automatically closes the file, even if an error occurs:

with Statement
with open("notes.txt", "r") as file:
    content = file.read()
    print(content)
# File is automatically closed here

Reading Files — Multiple Ways

Reading Methods
with open("data.txt", "r") as f:
    all_text = f.read()       # Read entire file as string
    
with open("data.txt", "r") as f:
    first_line = f.readline() # Read one line

with open("data.txt", "r") as f:
    all_lines = f.readlines() # Read all lines as list
    
with open("data.txt", "r") as f:
    for line in f:            # Best for large files
        print(line.strip())

Writing to Files

Writing Files
# Write (overwrites existing content)
with open("log.txt", "w") as f:
    f.write("System started
")
    f.write("All services online
")

# Append (adds to existing content)
with open("log.txt", "a") as f:
    f.write("New user logged in
")

Working with CSV Files

CSV Reading and Writing
import csv

# Writing CSV
with open("students.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Score", "Grade"])
    writer.writerow(["Suraj", 88, "B"])
    writer.writerow(["Priya", 94, "A"])

# Reading CSV
with open("students.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"{row['Name']}: {row['Score']}")

Working with JSON Files

JSON Read and Write
import json

config = {
    "app_name": "SRJahir Tech",
    "version": "2.0",
    "debug": False,
    "allowed_hosts": ["srjahir.in", "localhost"]
}

# Write JSON
with open("config.json", "w") as f:
    json.dump(config, f, indent=2)

# Read JSON
with open("config.json", "r") as f:
    loaded_config = json.load(f)
    print(loaded_config["app_name"])

Checking if File Exists

os.path Check
import os
if os.path.exists("data.txt"):
    with open("data.txt", "r") as f:
        print(f.read())
else:
    print("File not found")

In Part 9, we tackle error handling — how professional Python programs deal with failures without crashing.

Common Mistakes Beginners Make

Learning from common pitfalls saves hours of frustration. Here are the mistakes most beginners make in this area and how to avoid them.

The first mistake is trying to memorize syntax before understanding logic. Python syntax is simple — you could memorize it in a day. But if you do not understand why you are writing what you are writing, you will not be able to adapt when things change or when a problem looks slightly different. Always ask: what problem does this solve?

The second mistake is writing very long functions or very long scripts without breaking them into logical units. Real professional code is made of small, focused pieces that each do one thing well. The moment your code does two or three unrelated things in one block, it is time to split it up.

The third mistake is not reading error messages. Python's error messages are actually quite good. They tell you the file, the line number, the type of error, and often a description. Read the entire error before searching online. The answer is usually right there.

How This Topic Appears in Real Projects

In real codebases, every concept from this tutorial series appears constantly. Backend web applications built with Flask or Django use functions, classes, data structures, and error handling throughout every route and service. Data pipelines use loops and comprehensions to process thousands of records efficiently. CLI tools use argument parsing, file handling, and process management. DevOps automation scripts combine shell integration with Python logic to orchestrate deployments, monitor systems, and handle alerts.

The concepts that feel abstract right now will click into place the moment you start building something real. That is why the best way to learn is to pick a small project that solves a problem you actually have — even something simple like a personal expense tracker or a file organizer — and build it using everything you have learned so far.

Practice Exercise

Before moving to the next part, write a small program that uses what you learned in this section. Do not copy from anywhere. Start with a blank file and build it from memory. The struggle is the learning. If you get stuck, read the code examples again — do not just copy them. Understand each line, then close the examples and write the program yourself. This is how programming actually sticks.

Working with CSV Files

CSV (Comma-Separated Values) files are one of the most common data file formats. Python's built-in csv module makes reading and writing them straightforward:

CSV File Operations
import csv

# Writing a CSV file
students = [
    ["Name", "Score", "Grade"],
    ["Alice", 88, "B"],
    ["Bob", 95, "A"],
    ["Charlie", 72, "C"]
]

with open("students.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(students)

# Reading a CSV file
with open("students.csv", "r") as f:
    reader = csv.DictReader(f)  # DictReader gives each row as a dict
    for row in reader:
        print(f"{row['Name']}: {row['Score']} ({row['Grade']})")

The newline="" argument when writing CSV files prevents extra blank lines on Windows. DictReader uses the first row as headers and returns each subsequent row as a dictionary — more readable than indexed access.

JSON File Handling

JSON (JavaScript Object Notation) is the standard format for web APIs and configuration files. Python's json module handles serialization (Python objects to JSON text) and deserialization (JSON text to Python objects) seamlessly. Dictionaries become JSON objects, lists become JSON arrays, strings and numbers map directly. Understanding JSON file handling is essential for anyone working with APIs or web services.

Practice Exercise

Write a program that reads a list of student records from a CSV file, calculates the class average, finds the highest and lowest scores, and writes a summary report to a new text file. Include proper error handling for the case where the input file does not exist. This exercise combines file handling, data processing, and error handling in a realistic scenario.

Disclaimer: This content is for educational purposes only. SRJahir Tech does not guarantee any specific outcome, job placement, or exam result. Learning requires consistent effort and practical application.