File Handling
advancedPart of Python in Practice
Theory
File handling is essential for storing and retrieving data. Python's built-in open() function provides a straightforward interface for working with files.
The open() function takes a filename and a mode:
file = open("filename.txt", "r")File modes:
"r"— read (default). Opens file for reading. Error if file doesn't exist."w"— write. Creates a new file or overwrites existing."a"— append. Writes to the end of the file. Creates if not exists."r+"— read and write. File must exist."x"— exclusive creation. Fails if file exists.
Add "b" for binary mode ("rb", "wb") for non-text files like images.
Reading methods:
read()— reads the entire file as a stringreadline()— reads one line at a timereadlines()— returns a list of all lines
Writing methods:
write(string)— writes a string to the filewritelines(list)— writes a list of strings (no newlines added)
The with statement (context manager) automatically closes the file when the block exits, even if an exception occurs. This is the recommended approach:
with open("file.txt", "r") as file:
content = file.read()
# File is automatically closed hereException handling prevents crashes when file operations fail. Use try/except/finally:
try:
with open("file.txt", "r") as f:
data = f.read()
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
finally:
print("Operation attempted")The os module provides file system utilities:
os.path.exists(path)— check if file/directory existsos.path.isfile(path)— check if path is a fileos.path.join()— join path components safelyos.remove(path)— delete a file
The csv module handles comma-separated values files, providing csv.reader() and csv.writer() for structured data.
Practical Examples
Exercises
Journal App — Write and Read
Write a program that asks the user for their journal entry for today, then saves it to a file called 'journal.txt' with a timestamp. Then read and display the entire journal file.
Starter Code:
from datetime import datetime\n\nentry = input('Write your journal entry: ')\n# Save and displayExpected Output:
Write your journal entry: Had a great day learning Python!\nSaved to journal.txt\n--- Journal Entry ---\n2026-01-15 14:30: Had a great day learning Python!File Word Counter
Write a program that reads a text file (create one called 'sample.txt' with 4-5 lines of text) and counts: total words, total characters (excluding spaces), and the number of lines. Use exception handling if the file doesn't exist.
Starter Code:
# Create sample.txt first\nwith open('sample.txt', 'w') as f:\n f.write('...') # add your text\n\n# Then count words, chars, and linesExpected Output:
Lines: 4\nWords: 28\nCharacters (no spaces): 142CSV Grade Manager
Create a CSV file called 'grades.csv' with columns: Name, Math, Science, English. Write at least 3 student records with numeric scores. Then read the CSV and calculate each student's average. Print a report sorted by average (highest first).
Starter Code:
import csv\n\n# Write the CSV and then read and calculate averagesExpected Output:
Charlie: 93.3\nAlice: 88.3\nBob: 75.0Mini Quiz
Mini Quiz
Mini Project
Mini Project: Personal Diary Application
Build a diary application that allows users to write entries, read all entries, and search entries by keyword. Data is stored in a file.
Requirements:
Bonus Challenge
Export all entries to a CSV file with columns: Date, Entry.