File handling lets Python read existing data, write new output, append logs, and work with project files.
Use with open(...) so files are closed automatically even if an error happens while reading or writing.
Most beginner file issues come from the wrong path, missing files, wrong mode, or unexpected text encoding.
Python makes file I/O straightforward with the built-in open() function. Always use the with statement - it automatically closes the file even if an error occurs.
| Mode | Description |
|---|---|
| 'r' | Read (default) - error if file doesn't exist |
| 'w' | Write - creates file or overwrites existing |
| 'a' | Append - adds to end of file |
| 'x' | Create - error if file already exists |
| 'r+' | Read and write |
| 'b' | Binary mode (e.g., 'rb', 'wb') |
| 't' | Text mode (default) |
# Read entire file as a string
with open("data.txt", "r") as f:
content = f.read()
print(content)
# Read line by line (memory-efficient for large files)
with open("data.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes trailing newline
# Read all lines into a list
with open("data.txt", "r") as f:
lines = f.readlines()
print(lines) # ['line1\n', 'line2\n', ...]
# Read one line at a time
with open("data.txt", "r") as f:
first_line = f.readline()
second_line = f.readline()
# Specify encoding (important for non-ASCII text)
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
# Write (overwrites existing content)
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.write("Second line\n")
# Write multiple lines at once
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
# Append to existing file
with open("log.txt", "a") as f:
f.write("New log entry\n")
# Write with print() - convenient for formatted output
with open("report.txt", "w") as f:
print("Report Title", file=f)
print(f"Total: {42}", file=f)
import json
# Write JSON to file
data = {
"name": "Alice",
"age": 25,
"hobbies": ["coding", "reading"]
}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read JSON from file
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded["name"]) # Alice
print(loaded["hobbies"]) # ['coding', 'reading']
# Write list of records
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
]
with open("users.json", "w") as f:
json.dump(users, f, indent=2)
import csv
students = [
["Name", "Age", "Grade"],
["Alice", 20, "A"],
["Bob", 22, "B"],
]
with open("students.csv", "w", newline="", encoding="utf-8") as file:
csv.writer(file).writerows(students)
with open("students.csv", newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
print(f"{row['Name']}: {row['Grade']}")
Alice: A
Bob: B
from pathlib import Path
# Create path objects
p = Path("data/output.txt")
home = Path.home()
cwd = Path.cwd()
# Path operations
print(p.name) # output.txt
print(p.stem) # output
print(p.suffix) # .txt
print(p.parent) # data
# Check existence
print(p.exists())
print(p.is_file())
print(p.is_dir())
# Create directories
Path("new_folder/sub").mkdir(parents=True, exist_ok=True)
# Read and write (modern way)
p = Path("hello.txt")
p.write_text("Hello, World!")
content = p.read_text()
print(content)
# List files in directory
for f in Path(".").iterdir():
print(f)
# Find all Python files recursively
for py_file in Path(".").rglob("*.py"):
print(py_file)
# Delete file
p.unlink(missing_ok=True)
0 of 2 checked
Try this next
0 of 3 completed
with open() closes the file automatically, even if an error happens while processing the file.
r reads, w writes and replaces the file, and a appends to the end without deleting existing content.
Relative paths depend on the current working directory. Check where the program is running from.
Explore 500+ free tutorials across 20+ languages and frameworks.