Python File Handling
Read, write, and manage files — the right way.
Opening files — always use with
Python
# The 'with' block auto-closes the file — always prefer this
with open("data.txt", "r") as f:
content = f.read() # read entire file
print(content)
# File is closed here automatically
File modes
| Mode | Meaning |
|---|---|
"r" | Read (default). Error if file doesn't exist. |
"w" | Write. Creates or overwrites. |
"a" | Append. Creates if needed, adds to end. |
"x" | Exclusive create. Error if already exists. |
"r+" | Read and write. |
"rb" | Read binary (images, PDFs…) |
Reading
Python
with open("data.txt") as f:
whole = f.read() # entire file as one string
lines = f.readlines() # list of lines (includes
)
line1 = f.readline() # just one line
# Memory-efficient for large files:
with open("big.log") as f:
for line in f: # iterate line by line
print(line.strip())
Writing and appending
Python
# Write (overwrites if exists):
with open("output.txt", "w") as f:
f.write("Hello, World!
")
f.writelines(["line1
", "line2
"])
# Append (adds to end):
with open("output.txt", "a") as f:
f.write("One more line
")
JSON files
Python
import json
# Write JSON:
data = {"name": "Raman", "age": 28, "skills": ["Python", "SQL"]}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read JSON:
with open("data.json") as f:
loaded = json.load(f) # → dict
CSV files
Python
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerow({"name": "Raman", "age": 28})
with open("data.csv") as f:
for row in csv.DictReader(f):
print(row) # {'name': 'Raman', 'age': '28'}
pathlib — modern file paths
Python 3.4+
from pathlib import Path
p = Path("data.txt")
p.exists() # True/False
p.read_text() # read as string
p.write_text("content") # write string
p.parent # parent directory
p.suffix # ".txt"
p.stem # "data"