File Handling β
π Working with Files β
Python provides built-in functions to work with files. You can read from files, write to files, and manipulate file contents.
Opening Files β
python
# Basic file opening
file = open('filename.txt', 'r') # Read mode
file = open('filename.txt', 'w') # Write mode
file = open('filename.txt', 'a') # Append mode
# Always close files when done
file.close()File Modes β
python
# Read modes
'r' # Read (default)
'rb' # Read binary
# Write modes
'w' # Write (overwrites existing file)
'wb' # Write binary
'a' # Append (adds to end of file)
'ab' # Append binary
# Read and write
'r+' # Read and write
'w+' # Write and read (overwrites)
'a+' # Append and readπ Reading Files β
Reading Entire File β
python
# Method 1: read() - entire file as string
with open('data.txt', 'r') as file:
content = file.read()
print(content)
# Method 2: readlines() - list of lines
with open('data.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip()) # strip() removes newline charactersReading Line by Line β
python
# Method 1: readline() - one line at a time
with open('data.txt', 'r') as file:
line = file.readline()
while line:
print(line.strip())
line = file.readline()
# Method 2: Iterating over file object
with open('data.txt', 'r') as file:
for line in file:
print(line.strip())βοΈ Writing Files β
Writing Text β
python
# Write mode (overwrites existing file)
with open('output.txt', 'w') as file:
file.write('Hello, World!\n')
file.write('Python file handling\n')
# Write multiple lines
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('output.txt', 'w') as file:
file.writelines(lines)Appending to Files β
python
# Append mode (adds to end of file)
with open('log.txt', 'a') as file:
file.write('New log entry\n')
# Append with timestamp
from datetime import datetime
with open('log.txt', 'a') as file:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
file.write(f'[{timestamp}] Log message\n')π The with Statement β
The with statement ensures files are properly closed, even if an error occurs.
python
# Without with statement (not recommended)
file = open('data.txt', 'r')
try:
content = file.read()
print(content)
finally:
file.close()
# With statement (recommended)
with open('data.txt', 'r') as file:
content = file.read()
print(content)
# File is automatically closed hereπ File and Directory Operations β
Using os Module β
python
import os
# Check if file exists
if os.path.exists('filename.txt'):
print('File exists')
# Get file size
size = os.path.getsize('filename.txt')
print(f'File size: {size} bytes')
# List directory contents
files = os.listdir('.')
for file in files:
print(file)
# Create directory
os.makedirs('new_directory', exist_ok=True)
# Remove file
os.remove('filename.txt')
# Remove directory
os.rmdir('directory_name')Using pathlib (Modern Approach) β
python
from pathlib import Path
# Create Path object
file_path = Path('data.txt')
# Check if file exists
if file_path.exists():
print('File exists')
# Get file info
print(f'File name: {file_path.name}')
print(f'File suffix: {file_path.suffix}')
print(f'File parent: {file_path.parent}')
# Read file using pathlib
content = file_path.read_text()
print(content)
# Write file using pathlib
file_path.write_text('Hello from pathlib!')π§ Error Handling with Files β
python
def safe_read_file(filename):
try:
with open(filename, 'r') as file:
return file.read()
except FileNotFoundError:
print(f"File '{filename}' not found")
return None
except PermissionError:
print(f"Permission denied to read '{filename}'")
return None
except Exception as e:
print(f"Error reading file: {e}")
return None
# Usage
content = safe_read_file('data.txt')
if content:
print(content)ποΈ Working with CSV Files β
python
import csv
# Writing CSV
data = [
['Name', 'Age', 'City'],
['Alice', 25, 'New York'],
['Bob', 30, 'Boston'],
['Charlie', 35, 'Chicago']
]
with open('people.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
# Reading CSV
with open('people.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# Working with CSV as dictionary
with open('people.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(f"Name: {row['Name']}, Age: {row['Age']}")π§ Working with JSON Files β
python
import json
# Writing JSON
data = {
'name': 'Alice',
'age': 30,
'city': 'New York',
'hobbies': ['reading', 'swimming', 'coding']
}
with open('data.json', 'w') as file:
json.dump(data, file, indent=2)
# Reading JSON
with open('data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)
print(f"Name: {loaded_data['name']}")π Practice Examples β
Example 1: Word Counter β
python
def count_words_in_file(filename):
try:
with open(filename, 'r') as file:
content = file.read().lower()
words = content.split()
# Count words
word_count = {}
for word in words:
# Remove punctuation
cleaned_word = ''.join(char for char in word if char.isalnum())
if cleaned_word:
word_count[cleaned_word] = word_count.get(cleaned_word, 0) + 1
return word_count
except FileNotFoundError:
print(f"File '{filename}' not found")
return {}
# Usage
word_counts = count_words_in_file('text.txt')
for word, count in sorted(word_counts.items()):
print(f"{word}: {count}")Example 2: Log File Analyzer β
python
from datetime import datetime
def analyze_log_file(filename):
error_count = 0
warning_count = 0
info_count = 0
try:
with open(filename, 'r') as file:
for line in file:
line = line.strip()
if 'ERROR' in line:
error_count += 1
elif 'WARNING' in line:
warning_count += 1
elif 'INFO' in line:
info_count += 1
return {
'errors': error_count,
'warnings': warning_count,
'info': info_count
}
except FileNotFoundError:
print(f"Log file '{filename}' not found")
return None
# Usage
stats = analyze_log_file('application.log')
if stats:
print(f"Errors: {stats['errors']}")
print(f"Warnings: {stats['warnings']}")
print(f"Info: {stats['info']}")Example 3: Configuration Manager β
python
import json
from pathlib import Path
class ConfigManager:
def __init__(self, config_file='config.json'):
self.config_file = Path(config_file)
self.config = self.load_config()
def load_config(self):
if self.config_file.exists():
try:
return json.loads(self.config_file.read_text())
except json.JSONDecodeError:
print("Invalid JSON in config file")
return {}
return {}
def save_config(self):
self.config_file.write_text(json.dumps(self.config, indent=2))
def get(self, key, default=None):
return self.config.get(key, default)
def set(self, key, value):
self.config[key] = value
self.save_config()
# Usage
config = ConfigManager()
config.set('database_url', 'localhost:5432')
config.set('debug', True)
print(config.get('database_url')) # localhost:5432
print(config.get('timeout', 30)) # 30 (default value)Example 4: File Backup System β
python
import shutil
from datetime import datetime
from pathlib import Path
def backup_file(source_file, backup_dir='backups'):
try:
source_path = Path(source_file)
backup_path = Path(backup_dir)
# Create backup directory if it doesn't exist
backup_path.mkdir(exist_ok=True)
# Create backup filename with timestamp
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_filename = f"{source_path.stem}_{timestamp}{source_path.suffix}"
backup_file_path = backup_path / backup_filename
# Copy file to backup location
shutil.copy2(source_file, backup_file_path)
print(f"Backup created: {backup_file_path}")
return backup_file_path
except Exception as e:
print(f"Backup failed: {e}")
return None
# Usage
backup_file('important_data.txt')π― Key Takeaways β
- Always use
withstatement for file operations - Choose appropriate file modes ('r', 'w', 'a')
- Handle file exceptions properly
- Use
pathlibfor modern file path operations - CSV and JSON modules simplify structured data handling
- Close files properly to avoid resource leaks
- Check file existence before operations
- Use appropriate encoding for text files
Continue to: Exception Handling β