Syntax Cache
BlogMethodFeaturesHow It WorksBuild a Game
  1. Home
  2. Cheat Sheets
  3. Python
  4. Python File I/O Cheat Sheet
PythonCheat Sheet

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.

On this page
  1. 1open() Modes
  2. 2Reading Files
  3. 3Writing and Appending
  4. 4Context Managers (with statement)
  5. 5pathlib.Path (Modern Path Handling)
  6. 6Reading and Writing CSV
  7. 7Reading and Writing JSON
  8. 8Exception Handling for File Operations
  9. 9os.path Utilities (Legacy)
open() ModesReading FilesWriting and AppendingContext Managers (with statement)pathlib.Path (Modern Path Handling)Reading and Writing CSVReading and Writing JSONException Handling for File Operationsos.path Utilities (Legacy)

open() Modes

The mode argument controls read/write/append and text/binary.

Common modes
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
Mode summary table
# '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

Read entire file as string
with open('data.txt') as f:
    content = f.read()
len(content)   # => number of characters
Read all lines into a list
with open('data.txt') as f:
    lines = f.readlines()
lines[0]   # => 'first line\n'

readlines() keeps the trailing newline. Use line.strip() to remove it.

Iterate line by line (memory efficient)
with open('data.txt') as f:
    for line in f:
        print(line.strip())
Read with encoding
with open('data.txt', encoding='utf-8') as f:
    content = f.read()
Read first N characters
with open('data.txt') as f:
    head = f.read(100)   # first 100 characters

Writing and Appending

Write (creates or truncates)
with open('output.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('output.txt', 'w') as f:
    f.writelines(lines)

writelines() does NOT add newlines automatically. Include \n in each string.

Append to existing file
with open('log.txt', 'a') as f:
    f.write('New log entry\n')
print() to a file
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.

Basic with statement
with open('data.txt') as f:
    data = f.read()
# f is closed here, even if an exception occurred
Multiple files at once
with open('input.txt') as src, open('output.txt', 'w') as dst:
    dst.write(src.read())
Without with (manual close)
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.

Create and join paths
from pathlib import Path
p = Path('src') / 'lib' / 'utils.py'
str(p)   # => 'src/lib/utils.py'
Read and write with Path
p = Path('data.txt')
content = p.read_text(encoding='utf-8')
p.write_text('new content', encoding='utf-8')
Path inspection
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()   # => False
List directory contents
p = Path('src')
list(p.iterdir())           # all items
list(p.glob('*.py'))        # Python files
list(p.rglob('*.py'))       # recursive Python files
Create directories
Path('output/data').mkdir(parents=True, exist_ok=True)

Reading and Writing CSV

Read CSV rows
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 list
Read CSV as dicts
import csv
with open('data.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['name'], row['age'])
Write CSV
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

Read JSON file
import json
with open('config.json') as f:
    data = json.load(f)
data['name']   # => access like a dict
Write JSON file
import json
data = {'name': 'Alice', 'scores': [85, 92, 88]}
with open('output.json', 'w') as f:
    json.dump(data, f, indent=2)
JSON string (not file)
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.

FileNotFoundError
try:
    with open('missing.txt') as f:
        data = f.read()
except FileNotFoundError:
    data = ''   # graceful fallback
PermissionError
try:
    with open('/etc/shadow') as f:
        data = f.read()
except PermissionError:
    print('Access denied')
JSON decode error
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 = {}
Check before opening with pathlib
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.

Join paths
import os
os.path.join('src', 'lib', 'utils.py')
# => 'src/lib/utils.py'
Split path components
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')
Check existence
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
Learn Python in Depth
Python Error Handling Practice →Python Loops Practice →Python Strings Practice →
See Also
Error Handling →String Methods →

Start Practicing Python

Free daily exercises with spaced repetition. No credit card required.

← Back to Python Syntax Practice
Syntax Cache

Build syntax muscle memory with spaced repetition.

Product

  • Pricing
  • Our Method
  • Daily Practice
  • Design Patterns
  • Interview Prep

Resources

  • Blog
  • Compare
  • Cheat Sheets
  • Vibe Coding
  • Muscle Memory

Languages

  • Python
  • JavaScript
  • TypeScript
  • Rust
  • SQL
  • GDScript

Legal

  • Terms
  • Privacy
  • Contact

© 2026 Syntax Cache

Cancel anytime in 2 clicks. Keep access until the end of your billing period.

No refunds for partial billing periods.