Python File Handling Read, Write, Append Files is an important Python topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Python File Handling Read, Write, Append Files solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Python File Handling Read, Write, Append Files should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Python File Handling Read Write Append Files should be studied as a practical Python lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the python > file-handling page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
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
# Write CSV
students = [
["Name", "Age", "Grade"],
["Alice", 20, "A"],
["Bob", 22, "B"],
["Charlie", 21, "A"],
]
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(students)
# Read CSV
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# DictReader - rows as dicts
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['Name']}: {row['Grade']}")
# DictWriter - write from dicts
with open("output.csv", "w", newline="") as f:
fieldnames = ["name", "score"]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"name": "Alice", "score": 95})
writer.writerow({"name": "Bob", "score": 87})
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)
When studying Python File Handling Read, Write, Append Files, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In Python, Python File Handling Read, Write, Append Files becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
def review_python-file-handling-read-write-append-files():
value = "sample"
if value:
print("Python File Handling Read Write Append Files: normal path is ready")
else:
print("Python File Handling Read Write Append Files: handle the empty path first")
review_python-file-handling-read-write-append-files()
items = []
if not items:
print("Python File Handling Read Write Append Files: no data available, show a fallback")
else:
print(items[0])
Memorizing Python File Handling Read Write Append Files without the situation where it is useful.
Connect Python File Handling Read Write Append Files to a concrete Python task.
Testing Python File Handling Read Write Append Files only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Python File Handling Read Write Append Files.
Memorizing Python File Handling Read Write Append Files without the situation where it is useful.
Connect Python File Handling Read Write Append Files to a concrete Python task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in Python, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.