Basic File Operations
# Always use context managers
with open('data.txt', 'r') as f:
content = f.read()
# Reading line by line
with open('data.txt', 'r') as f:
for line in f:
print(line.strip())
# Writing to a file
with open('output.txt', 'w') as f:
f.write('Hello, World!\n')
Working with CSV
import csv
with open('data.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
print(row['name'], row['email'])
Working with JSON
import json
with open('config.json', 'r') as f:
config = json.load(f)
data = {'users': [{'name': 'Alice'}]}
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
Pathlib (Modern Approach)
from pathlib import Path
p = Path('data') / 'files' / 'output.txt'
p.write_text('Hello!')
content = p.read_text()
for file in Path('data').glob('*.txt'):
print(file.name)
Ready to Level Up Your Coding Skills?
Join Coderz Club and learn to code with challenges, battles, and an AI mentor.
Join Coderz Club Free →