Python File Handling Cheat Sheet
Reading and writing files in Python covering open modes, line iteration, pathlib path operations, and CSV/JSON serialization.
1 PageBeginnerApr 10, 2026
Opening & Modes
The with statement guarantees the file is closed.
python
with open("data.txt", "r") as f: # 'r' read (default) contents = f.read()# file is automatically closed here, even on exception# common modes:# 'r' read (default) 'w' write, truncates existing file# 'a' append 'x' create, fails if file exists# 'rb' read binary 'r+' read and write
Reading Files
Three common ways to read file contents.
python
with open("data.txt") as f: contents = f.read() # entire file as one stringwith open("data.txt") as f: lines = f.readlines() # list of lines, keeps '\n'with open("data.txt") as f: for line in f: # memory-efficient, one line at a time print(line.strip())
Writing & Appending
Creating and adding to files.
python
with open("out.txt", "w") as f: f.write("Hello\n") f.writelines(["line1\n", "line2\n"])with open("out.txt", "a") as f: f.write("appended line\n") # adds without erasing existing content
pathlib for Path Operations
The modern, object-oriented way to work with file paths.
python
from pathlib import Pathp = Path("data") / "file.txt" # cross-platform path joiningp.exists()p.is_file()p.read_text()p.write_text("content")list(Path(".").glob("*.py")) # all .py files in current dir
CSV & JSON
Reading and writing structured data formats.
python
import csvwith open("data.csv", newline="") as f: reader = csv.DictReader(f) for row in reader: print(row)import jsonwith open("data.json") as f: data = json.load(f)with open("out.json", "w") as f: json.dump(data, f, indent=2)
Pro Tip
Always specify `encoding="utf-8"` explicitly when opening text files — the default encoding is platform-dependent, so code that works on your machine can silently misread files on a server with a different locale.
Was this cheat sheet helpful?
Previous
Python Exception Handling Cheat Sheet
Next
Python Multithreading & Multiprocessing Cheat Sheet
Explore Topics
#PythonFileHandling#PythonFileHandlingCheatSheet#Programming#Beginner#OpeningModes#ReadingFiles#WritingAppending#PathlibForPathOperations#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance