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.
# 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 automatically closes the file, even if an error occurs:
with open("notes.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed here
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())
# 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
")
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']}")
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"])
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.
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.
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.
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.
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:
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 (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.
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.