Docs
README
07 - File Handling
📌 What You'll Learn
- •Opening and closing files
- •Reading files (text and binary)
- •Writing files
- •File modes
- •Working with file paths
- •JSON and CSV files
- •Context managers
📂 Opening and Closing Files
Basic File Operations
# Open a file
file = open('myfile.txt', 'r') # 'r' = read mode
# Do something with the file
content = file.read()
# Always close the file!
file.close()
Context Manager (Recommended!)
# Automatically closes the file
with open('myfile.txt', 'r') as file:
content = file.read()
# File is automatically closed here
📖 File Modes
| Mode | Description |
|---|---|
'r' | Read (default) - file must exist |
'w' | Write - creates new or truncates existing |
'a' | Append - adds to end of file |
'x' | Exclusive create - fails if file exists |
'r+' | Read and write |
'w+' | Write and read (truncates) |
'a+' | Append and read |
'b' | Binary mode (add to other modes) |
't' | Text mode (default) |
# Examples
open('file.txt', 'r') # Read text
open('file.txt', 'w') # Write text
open('file.txt', 'rb') # Read binary
open('file.txt', 'wb') # Write binary
open('file.txt', 'r+') # Read and write
📖 Reading Files
Read Entire File
with open('file.txt', 'r') as f:
content = f.read()
print(content)
Read Line by Line
# Read all lines into a list
with open('file.txt', 'r') as f:
lines = f.readlines() # List of lines with \n
# Read lines without \n
with open('file.txt', 'r') as f:
lines = f.read().splitlines()
# Iterate line by line (memory efficient)
with open('file.txt', 'r') as f:
for line in f:
print(line.strip()) # Remove trailing whitespace
Read Specific Amount
with open('file.txt', 'r') as f:
# Read first 100 characters
chunk = f.read(100)
# Read one line
line = f.readline()
# Read first 5 lines
for i in range(5):
line = f.readline()
print(line)
File Position
with open('file.txt', 'r') as f:
# Get current position
pos = f.tell()
# Move to position
f.seek(0) # Beginning
f.seek(10) # 10th byte
f.seek(0, 2) # End of file
✏️ Writing Files
Write Text
# Write (overwrites existing content)
with open('file.txt', 'w') as f:
f.write('Hello, World!\n')
f.write('Second line\n')
# Write multiple lines
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('file.txt', 'w') as f:
f.writelines(lines)
Append to File
with open('file.txt', 'a') as f:
f.write('This is appended\n')
Print to File
with open('file.txt', 'w') as f:
print('Hello', file=f)
print('World', file=f)
📁 Working with Paths
Using os.path
import os
# Current directory
current = os.getcwd()
# Join paths
path = os.path.join('folder', 'subfolder', 'file.txt')
# Check existence
exists = os.path.exists(path)
is_file = os.path.isfile(path)
is_dir = os.path.isdir(path)
# Get parts
dirname = os.path.dirname('/path/to/file.txt') # /path/to
basename = os.path.basename('/path/to/file.txt') # file.txt
name, ext = os.path.splitext('file.txt') # ('file', '.txt')
# Absolute path
abs_path = os.path.abspath('file.txt')
Using pathlib (Modern Approach)
from pathlib import Path
# Create path
p = Path('folder') / 'subfolder' / 'file.txt'
# Properties
print(p.exists())
print(p.is_file())
print(p.parent) # folder/subfolder
print(p.name) # file.txt
print(p.stem) # file
print(p.suffix) # .txt
# Read/write with pathlib
path = Path('file.txt')
path.write_text('Hello, World!')
content = path.read_text()
# Binary
path.write_bytes(b'binary data')
data = path.read_bytes()
# List files
for file in Path('.').glob('*.txt'):
print(file)
# Recursive search
for file in Path('.').rglob('*.py'):
print(file)
📊 Working with JSON
import json
# Python to JSON
data = {
'name': 'Alice',
'age': 25,
'hobbies': ['reading', 'coding']
}
# Write to file
with open('data.json', 'w') as f:
json.dump(data, f, indent=2)
# Read from file
with open('data.json', 'r') as f:
loaded = json.load(f)
# String conversion
json_str = json.dumps(data, indent=2)
parsed = json.loads(json_str)
📋 Working with CSV
import csv
# Write CSV
data = [
['Name', 'Age', 'City'],
['Alice', 25, 'New York'],
['Bob', 30, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
# Read CSV
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
# Dictionary CSV
with open('data.csv', 'w', newline='') as f:
fieldnames = ['name', 'age', 'city']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'name': 'Alice', 'age': 25, 'city': 'NYC'})
with open('data.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
print(row['name'], row['age'])
🔒 Exception Handling with Files
# Handle file errors
try:
with open('nonexistent.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
except IOError as e:
print(f"I/O error: {e}")
🔧 Useful File Operations
Copy, Move, Delete
import shutil
import os
# Copy file
shutil.copy('source.txt', 'destination.txt')
# Copy with metadata
shutil.copy2('source.txt', 'destination.txt')
# Move/rename
shutil.move('old_name.txt', 'new_name.txt')
# Delete file
os.remove('file.txt')
# Delete directory (empty)
os.rmdir('empty_folder')
# Delete directory (with contents)
shutil.rmtree('folder_with_contents')
Create Directories
import os
from pathlib import Path
# os way
os.makedirs('folder/subfolder', exist_ok=True)
# pathlib way
Path('folder/subfolder').mkdir(parents=True, exist_ok=True)
Temporary Files
import tempfile
# Create temporary file
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
f.write('Temporary content')
temp_path = f.name
# Create temporary directory
with tempfile.TemporaryDirectory() as tmpdir:
print(f"Created temp dir: {tmpdir}")
# Directory is deleted when block ends
📝 Binary Files
# Read binary
with open('image.png', 'rb') as f:
data = f.read()
# Write binary
with open('copy.png', 'wb') as f:
f.write(data)
# Reading in chunks
with open('large_file.bin', 'rb') as f:
while True:
chunk = f.read(1024) # Read 1KB at a time
if not chunk:
break
# Process chunk
🎯 Next Steps
After mastering file handling, proceed to 08_error_handling to learn about exceptions!