Opening Files
Use the open() function to open files. Always use the with statement to ensure files are properly closed:
# Open file for reading
with open('data.txt', 'r') as file:
content = file.read()
print(content)
# File is automatically closed when exiting the 'with' block
File Modes
Different modes for different operations:
'r' # Read (default) - file must exist
'w' # Write - creates file, overwrites if exists
'a' # Append - adds to end of file
'x' # Exclusive creation - fails if file exists
'r+' # Read and write
'b' # Binary mode (e.g., 'rb', 'wb')
't' # Text mode (default)
Reading Files
Read Entire File
with open('data.txt', 'r') as file:
content = file.read() # Read entire file as string
print(content)
Read Line by Line
with open('data.txt', 'r') as file:
for line in file:
print(line.strip()) # strip() removes newline
# Or read all lines into list
with open('data.txt', 'r') as file:
lines = file.readlines() # List of lines
Read First N Lines
with open('data.txt', 'r') as file:
first_line = file.readline() # Read one line
first_three = [file.readline() for _ in range(3)]
Writing Files
Write Text
# Write (overwrites existing file)
with open('output.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is line 2\n")
# Append to file
with open('output.txt', 'a') as file:
file.write("This is appended\n")
Write Multiple Lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('output.txt', 'w') as file:
file.writelines(lines)
# Or use join
with open('output.txt', 'w') as file:
file.write('\n'.join(lines))
Working with Paths
Use os.path or pathlib for file paths:
import os
from pathlib import Path
# Using os.path
file_path = os.path.join('folder', 'subfolder', 'file.txt')
exists = os.path.exists(file_path)
# Using pathlib (recommended)
file_path = Path('folder') / 'subfolder' / 'file.txt'
exists = file_path.exists()
# Get absolute path
abs_path = os.path.abspath('file.txt')
abs_path = Path('file.txt').resolve()
Error Handling
Handle file errors gracefully:
try:
with open('data.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
except Exception as e:
print(f"Error: {e}")
Working with JSON
Read and write JSON files:
import json
# Write JSON
data = {"name": "Alice", "age": 25, "city": "NYC"}
with open('data.json', 'w') as file:
json.dump(data, file, indent=2)
# Read JSON
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
Working with CSV
Read and write CSV files:
import csv
# Write CSV
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 25, 'NYC'])
writer.writerow(['Bob', 30, 'LA'])
# Read CSV
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Best Practices
- Always use 'with': Ensures files are closed automatically
- Handle exceptions: Files might not exist or be accessible
- Use appropriate mode: 'r' for reading, 'w' for writing, 'a' for appending
- Close files explicitly: If not using 'with', always call close()
- Use pathlib: More modern and cross-platform than os.path
Next Steps
Learn about exception handling to handle file errors properly, or explore modules like json and csv for specialized file formats.