Python File I/O Cheat Sheet
Quick-reference for file reading, writing, and path manipulation. Each section includes copy-ready snippets with inline output comments.
open() Modes
The mode argument controls read/write/append and text/binary.
open('f.txt', 'r') # Read text (default)
open('f.txt', 'w') # Write text (truncates!)
open('f.txt', 'a') # Append text
open('f.txt', 'x') # Create (fails if exists)
open('f.png', 'rb') # Read binary
open('f.png', 'wb') # Write binary# 'r' read (file must exist)
# 'w' write (creates or truncates)
# 'a' append (creates or appends)
# 'x' exclusive (fails if file exists)
# 'b' binary mode (add to above: 'rb', 'wb')
# '+' read+write (add to above: 'r+', 'w+')'w' destroys existing content. Use 'a' to append or 'x' to prevent overwriting.
Reading Files
with open('data.txt') as f:
content = f.read()
len(content) # => number of characterswith open('data.txt') as f:
lines = f.readlines()
lines[0] # => 'first line\n'readlines() keeps the trailing newline. Use line.strip() to remove it.
with open('data.txt') as f:
for line in f:
print(line.strip())with open('data.txt', encoding='utf-8') as f:
content = f.read()with open('data.txt') as f:
head = f.read(100) # first 100 charactersWriting and Appending
with open('output.txt', 'w') as f:
f.write('Hello, world!\n')
f.write('Second line\n')lines = ['line 1\n', 'line 2\n', 'line 3\n']
with open('output.txt', 'w') as f:
f.writelines(lines)writelines() does NOT add newlines automatically. Include \n in each string.
with open('log.txt', 'a') as f:
f.write('New log entry\n')with open('output.txt', 'w') as f:
print('Hello', 'world', sep=', ', file=f)
# writes: 'Hello, world\n'Context Managers (with statement)
The with statement ensures the file is closed automatically, even if an exception occurs.
with open('data.txt') as f:
data = f.read()
# f is closed here, even if an exception occurredwith open('input.txt') as src, open('output.txt', 'w') as dst:
dst.write(src.read())f = open('data.txt')
try:
data = f.read()
finally:
f.close() # Must close manually!Always prefer the with statement. Manual close is error-prone.
pathlib.Path (Modern Path Handling)
pathlib provides an object-oriented interface for filesystem paths. Prefer it over os.path for new code.
from pathlib import Path
p = Path('src') / 'lib' / 'utils.py'
str(p) # => 'src/lib/utils.py'p = Path('data.txt')
content = p.read_text(encoding='utf-8')
p.write_text('new content', encoding='utf-8')p = Path('/home/user/project/main.py')
p.name # => 'main.py'
p.stem # => 'main'
p.suffix # => '.py'
p.parent # => PosixPath('/home/user/project')
p.exists() # => True or False
p.is_file() # => True or False
p.is_dir() # => Falsep = Path('src')
list(p.iterdir()) # all items
list(p.glob('*.py')) # Python files
list(p.rglob('*.py')) # recursive Python filesPath('output/data').mkdir(parents=True, exist_ok=True)Reading and Writing CSV
import csv
with open('data.csv') as f:
reader = csv.reader(f)
header = next(reader) # first row as list
for row in reader:
print(row) # each row is a listimport csv
with open('data.csv') as f:
reader = csv.DictReader(f)
for row in reader:
print(row['name'], row['age'])import csv
rows = [['name', 'age'], ['Alice', 30], ['Bob', 25]]
with open('out.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(rows)Pass newline='' to open() when writing CSV to prevent double line endings on Windows.
Reading and Writing JSON
import json
with open('config.json') as f:
data = json.load(f)
data['name'] # => access like a dictimport json
data = {'name': 'Alice', 'scores': [85, 92, 88]}
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)import json
s = json.dumps({'a': 1}) # => '{"a": 1}'
d = json.loads(s) # => {'a': 1}Exception Handling for File Operations
Handle the specific exceptions that file operations raise.
try:
with open('missing.txt') as f:
data = f.read()
except FileNotFoundError:
data = '' # graceful fallbacktry:
with open('/etc/shadow') as f:
data = f.read()
except PermissionError:
print('Access denied')import json
try:
with open('config.json') as f:
config = json.load(f)
except FileNotFoundError:
config = {}
except json.JSONDecodeError as e:
print(f'Invalid JSON: {e}')
config = {}from pathlib import Path
p = Path('data.txt')
if p.exists() and p.is_file():
content = p.read_text()Prefer try/except over existence checks (EAFP). The file can be deleted between check and read.
os.path Utilities (Legacy)
os.path still works and appears in older codebases. Prefer pathlib for new code.
import os
os.path.join('src', 'lib', 'utils.py')
# => 'src/lib/utils.py'import os
os.path.basename('/home/user/file.txt') # => 'file.txt'
os.path.dirname('/home/user/file.txt') # => '/home/user'
os.path.splitext('main.py') # => ('main', '.py')import os
os.path.exists('data.txt') # => True or False
os.path.isfile('data.txt') # => True if regular file
os.path.isdir('src') # => True if directory