Python Lesson 16: File Handling
Programs often need to save data to files or read data from files. Python makes file handling simple and safe with the with statement.
Writing to a File
# "w" = write mode (creates file, overwrites if exists)
with open("notes.txt", "w") as file:
file.write("Hello from Python!\n")
file.write("Second line\n")
# File is automatically closed after the with block
# This is the safest way to work with files!
Reading from a File
# "r" = read mode (file must exist)
with open("notes.txt", "r") as file:
content = file.read() # read entire file
print(content)
# Read line by line
with open("notes.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes newline \n
# Read all lines into a list
with open("notes.txt", "r") as file:
lines = file.readlines()
print(lines)
Appending to a File
# "a" = append mode (adds to end, does not overwrite)
with open("notes.txt", "a") as file:
file.write("This line is added at the end\n")
# Now the file has 3 lines
Handling File Errors
# What if the file does not exist?
try:
with open("missing.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("File not found!")
content = ""
# Check if file exists before opening
import os
if os.path.exists("notes.txt"):
with open("notes.txt") as f:
print(f.read())
Working with CSV Data
# Save a list of students to a file
students = [("Alice", 95), ("Bob", 87), ("Charlie", 92)]
with open("students.csv", "w") as f:
f.write("Name,Score\n")
for name, score in students:
f.write(f"{name},{score}\n")
# Read it back
with open("students.csv", "r") as f:
for line in f:
print(line.strip())
🏋️ Practice Task
Build a simple diary. Create a program that: (1) asks user for a diary entry, (2) saves it to diary.txt with today’s date at the top, (3) reads and displays the entire diary. Run it twice to prove appending works.
💡 Hint: Use “a” mode to append. Use from datetime import date and str(date.today()) for the date.