Lesson 4 • Intermediate
File Handling in Python
Learn to read, write, and manage files to save data permanently.
What You'll Learn in This Lesson
- ✓Why files are essential for saving data permanently
- ✓File modes: read (r), write (w), append (a), create (x)
- ✓How to safely open files using the with statement
- ✓How to read entire files, line by line, or as a list
- ✓How to write and append to files
- ✓How to check if a file exists and work with CSV/JSON
1. Why Learn File Handling?
When your program ends, all variables are lost. Files let you save data permanently so it survives after your program closes.
What Can You Do with Files?
- Save user data — Store settings, preferences, scores
- Read data — Load configuration, import information
- Create logs — Track events and errors
- Process data — Work with CSV, JSON, or text files
2. Opening Files with open()
Use the open() function to work with files. You specify the filename and a mode that tells Python what you want to do.
| Mode | Name | What It Does |
|---|---|---|
| "r" | Read | Open for reading (file must exist) |
| "w" | Write | Create new or overwrite existing |
| "a" | Append | Add to end (keeps existing content) |
| "x" | Create | Create new (error if file exists) |
"w" will delete all existing contentin the file! Use "a" if you want to add to the file instead.3. The with Statement (Best Practice)
Always use the with statement when working with files. It automatically closes the file when you are done, even if an error occurs.
file = open("data.txt", "r")
content = file.read()
file.close() # Easy to forget!with open("data.txt", "r") as file:
content = file.read()
# Automatically closed!with open(...) as file: — it is the safest and cleanest way to handle files in Python.4. Reading Files
There are several ways to read file content:
| Method | What It Returns | Best For |
|---|---|---|
| .read() | Entire file as one string | Small files |
| .readline() | One line at a time | Processing line by line |
| .readlines() | List of all lines | When you need a list |
| for line in file: | Each line (loop) | Large files (memory efficient) |
Try It: Reading Files
Different ways to read file content
# Simulating file reading (since we can't create real files here)
file_content = """Line 1: Hello Python!
Line 2: File handling is useful.
Line 3: Keep practicing!"""
# Simulate .read() - entire file
print("=== read() - Entire file ===")
print(file_content)
# Simulate .readlines() - list of lines
print("\n=== readlines() - List of lines ===")
lines = file_content.split("\n")
print(lines)
# Simulate looping through lines
print("\n=== Loop through lines ===")
for i, line in enumerate(lines, 1):
...5. Writing to Files
Use mode "w" to write to a file. This creates a new file or overwrites an existing one.
Try It: Writing Files
Save data to a file
# Simulating file writing
output = []
# Simulate writing lines
output.append("Hello, World!")
output.append("This is line 2.")
output.append("Python file handling is easy!")
print("=== File would contain ===")
for line in output:
print(line)
# Real code would be:
# with open("output.txt", "w") as file:
# file.write("Hello, World!\n")
# file.write("This is line 2.\n").write() does not automatically add line breaks. Add \n at the end of each line if you want separate lines.6. Appending to Files
Use mode "a" to add content to the end of a file without deleting existing content.
Try It: Appending
Add to files without overwriting
# Simulating append behavior
existing_content = [
"Log entry 1: Started app",
"Log entry 2: User logged in"
]
print("=== Existing content ===")
for line in existing_content:
print(line)
# Append new entries
existing_content.append("Log entry 3: New action performed")
existing_content.append("Log entry 4: User logged out")
print("\n=== After appending ===")
for line in existing_content:
print(line)| Mode | Existing Content | Use Case |
|---|---|---|
| "w" | Deleted (overwritten) | Creating new files, saving fresh data |
| "a" | Kept (added to) | Logs, history, collecting data |
7. Checking if a File Exists
Before reading a file, check if it exists to avoid errors:
Try It: Check File Exists
Verify file exists before opening
import os
# Check if file exists
filename = "data.txt"
# Simulating os.path.exists behavior
files_on_disk = ["notes.txt", "config.json", "data.txt"]
if filename in files_on_disk:
print(f"'{filename}' exists! Safe to open.")
else:
print(f"'{filename}' not found.")
# Real code:
# if os.path.exists("data.txt"):
# with open("data.txt", "r") as file:
# content = file.read()
# else:
# print("File not found")8. Handling File Errors
Use try-except to handle errors gracefully when working with files:
| Error | Cause |
|---|---|
| FileNotFoundError | File does not exist (reading mode) |
| PermissionError | No permission to access file |
| IsADirectoryError | Tried to open a folder as a file |
Try It: Error Handling
Handle file errors gracefully
# Safe file reading with try-except
def read_file_safely(filename):
try:
# Simulate file operations
if filename == "missing.txt":
raise FileNotFoundError(f"No such file: '{filename}'")
elif filename == "protected.txt":
raise PermissionError(f"Access denied: '{filename}'")
else:
return f"Content of {filename}: Hello World!"
except FileNotFoundError:
return "Error: File not found."
except PermissionError:
...9. Working with CSV Files
CSV (Comma-Separated Values) is a common format for spreadsheet data. Python has a built-in csv module to work with it.
Try It: CSV Files
Read and write spreadsheet data
import csv
from io import StringIO
# Create CSV data in memory
csv_data = StringIO()
writer = csv.writer(csv_data)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", 25, "London"])
writer.writerow(["Bob", 30, "Paris"])
writer.writerow(["Charlie", 35, "Tokyo"])
# Read the CSV data
csv_data.seek(0)
print("=== CSV Content ===")
reader = csv.reader(csv_data)
for row in reader:
print(row)
# Using DictReader for easier access
csv_data.seek(0)
print("\n=== As Dictionaries ===")
d
...10. Working with JSON Files
JSON (JavaScript Object Notation) is used for configuration files and APIs. Python can easily convert between JSON and dictionaries.
| Function | What It Does |
|---|---|
| json.dumps(obj) | Convert Python dict → JSON string |
| json.loads(str) | Convert JSON string → Python dict |
| json.dump(obj, file) | Write dict to JSON file |
| json.load(file) | Read JSON file to dict |
Try It: JSON Files
Work with JSON data
import json
# Python dictionary
data = {
"name": "Alice",
"age": 25,
"skills": ["Python", "JavaScript"],
"active": True
}
# Convert to JSON string (for saving to file)
json_string = json.dumps(data, indent=2)
print("=== JSON String ===")
print(json_string)
# Convert back to Python dict (for reading from file)
parsed = json.loads(json_string)
print("\n=== Back to Python ===")
print(f"Name: {parsed['name']}")
print(f"Skills: {parsed['skills']}")11. Common Mistakes to Avoid
| Mistake | Problem | Solution |
|---|---|---|
| Forgetting to close file | Data may not save, file locked | Use with statement |
| Using "w" instead of "a" | Existing data deleted | Double-check your mode |
| Forgetting \n | All text on one line | Add \n after each line |
| Reading non-existent file | FileNotFoundError | Check with os.path.exists() |
| Wrong encoding | Strange characters appear | Add encoding="utf-8" |
12. Practical Examples
Example 1: Simple Note Saver
Note Saver
Save notes to a file
# Simple note saver simulation
notes = []
def save_note(note):
notes.append(note)
print(f"Saved: {note}")
def show_notes():
print("\n=== Your Notes ===")
for i, note in enumerate(notes, 1):
print(f"{i}. {note}")
# Add some notes
save_note("Buy groceries")
save_note("Call mom")
save_note("Finish Python lesson")
# Display all notes
show_notes()
# Real implementation:
# with open("notes.txt", "a") as f:
# f.write(note + "\n")Example 2: Word Counter
Word Counter
Analyze text content
# Count words, lines, and characters in text
text = """Python is a great programming language.
It is easy to learn and very powerful.
Many developers love using Python for various projects."""
lines = text.split("\n")
words = text.split()
chars = len(text)
print("=== Text Analysis ===")
print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}")
print(f"Characters: {chars}")
# Count word frequency
word_count = {}
for word in words:
word = word.lower().strip(".,!?")
word_count[word] =
...Example 3: Simple Log System
Log System
Create activity logs with timestamps
from datetime import datetime
# Simple logging system
log = []
def log_event(event):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
entry = f"[{timestamp}] {event}"
log.append(entry)
print(entry)
# Log some events
log_event("Application started")
log_event("User logged in")
log_event("File saved successfully")
log_event("User logged out")
print("\n=== Complete Log ===")
for entry in log:
print(entry)Summary: Quick Reference
| Operation | Code |
|---|---|
| Read entire file | with open("f.txt", "r") as f: text = f.read() |
| Read lines | for line in file: |
| Write (overwrite) | with open("f.txt", "w") as f: f.write("text") |
| Append | with open("f.txt", "a") as f: f.write("more") |
| Check exists | os.path.exists("f.txt") |
| Read CSV | csv.reader(file) |
| Read JSON | json.load(file) |
| Write JSON | json.dump(data, file) |
Lesson 9 complete — your programs can now save and load data!
Reading, writing, appending, CSV, JSON — you know how to work with files safely using the with statement. Your programs can now remember things between runs.
🚀 Up next: Exception Handling — learn to catch errors gracefully so your programs never crash unexpectedly.
Sign up for free to track which lessons you've completed and get learning reminders.