File Handling

Read, write, and manage files

INTERMEDIATE

File Handling Mastery

Read from logs, save user data, process CSV files, backup configurations. Every real application needs persistent data storage.

File Modes Reference

Python's open() function uses modes to specify read/write behavior and text/binary format.

Mode Action Creates? Error if Missing
'r' Read only No Yes
'w' Write (overwrite) Yes No
'a' Append Yes No
'r+' Read + Write No Yes
'b' Binary mode - -

Basic Read & Write

Writing Files

# Always use 'with' (auto-closes file) with open('notes.txt', 'w') as file: file.write("Hello, Python!\n") file.write("Line 2\n") file.writelines(["Line 3\n", "Line 4\n"]) print("File created!")

Reading Files

# Read entire file with open('notes.txt', 'r') as file: content = file.read() print(content) # Read line by line with open('notes.txt', 'r') as file: for line_num, line in enumerate(file, 1): print(f"Line {line_num}: {line.strip()}") # Read all lines as list with open('notes.txt', 'r') as file: lines = file.readlines()

Context Managers (with)

✅ Automatic Cleanup

with open('data.txt', 'w') as f: f.write("Safe!") # File AUTOMATICALLY closed ✓

✅ Exception Safe

try: with open('data.txt', 'r') as f: data = f.read() except FileNotFoundError: print("File missing") # File closed even on error ✓

Manual vs Context Manager

# ❌ BAD - Manual close (forget = crash!) file = open('test.txt', 'w') file.write("data") file.close() # Easy to forget! # ✅ GOOD - Context manager with open('test.txt', 'w') as file: file.write("data") # Always closes ✓

CSV & JSON Processing

CSV - Tabular Data

import csv # Write CSV with open('users.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['name', 'age', 'city']) writer.writerows([ ['Alice', 25, 'NYC'], ['Bob', 30, 'LA'] ]) # Read CSV with open('users.csv', 'r') as file: reader = csv.DictReader(file) for row in reader: print(f"{row['name']} is {row['age']}")

JSON - Structured Data

import json user_data = { "name": "Alice", "skills": ["Python", "SQL", "Docker"], "active": True } # Write JSON with open('user.json', 'w') as file: json.dump(user_data, file, indent=2) # Read JSON with open('user.json', 'r') as file: data = json.load(file) print(data["name"]) # Alice

Advanced File Operations

File Paths & Directories

import os from pathlib import Path # Current directory print(os.getcwd()) # List files print(os.listdir('.')) # Pathlib (modern) folder = Path('data') folder.mkdir(exist_ok=True) # Check existence if Path('notes.txt').exists(): print("File found!") # File size print(f"Size: {Path('notes.txt').stat().st_size} bytes")

Copy, Move, Delete

import shutil # Copy file shutil.copy('source.txt', 'backup.txt') # Move/rename shutil.move('old.txt', 'new.txt') # Delete file # os.remove('temp.txt') # Single file # shutil.rmtree('temp_dir') # Directory

Log File Analysis

def analyze_log(filename): errors = 0 warnings = 0 with open(filename, 'r') as file: for line in file: if 'ERROR' in line: errors += 1 elif 'WARNING' in line: warnings += 1 return {'errors': errors, 'warnings': warnings} stats = analyze_log('app.log') print(f"Errors: {stats['errors']}, Warnings: {stats['warnings']}")

Configuration Files

# config.ini style config = { 'database': 'localhost:5432', 'debug': True, 'timeout': 30 } with open('config.txt', 'w') as f: for key, value in config.items(): f.write(f"{key}={value}\n")

File Handling Projects

1. Todo List Saver

Save/load todo list to JSON. Add, complete, delete tasks.

2. CSV Gradebook

Read student grades CSV → calculate averages → write report.

3. Log Analyzer

Parse server logs → count errors by type → generate summary.

4. Backup Utility

Copy folder recursively → compress → timestamp naming.

Robust Error Handling

import os def safe_read(filename): try: if not os.path.exists(filename): raise FileNotFoundError(f"{filename} not found") with open(filename, 'r') as file: return file.read() except PermissionError: return "Permission denied" except UnicodeDecodeError: return "Invalid file encoding" except Exception as e: return f"Error: {e}" content = safe_read('missing.txt') print(content)

File Handling Pro!

💾 Production Applications:

📊 Data Processing
CSV/JSON pipelines
📝 Log Analysis
Error tracking systems
💾 Backup Tools
Automated file sync
📈 Config Management
App settings loader
🔄 Data Migration
Database import/export

Production-ready data persistence unlocked!
Next: Modules → Error Handling → Deployment