Writing & Appending Files
Write to files with 'w' mode (overwrites) or 'a' mode (appends). Always use context managers (with) to ensure files are properly closed.
15 min•By Priygop Team•Updated 2026
Writing Files
Writing Files
import io
# Write mode ('w') — overwrites!
output = io.StringIO()
output.write("Hello, World!\n")
output.write("Python is awesome!\n")
output.write(f"2 + 3 = {2 + 3}\n")
print("Written content:")
print(output.getvalue())
# Writing multiple lines
output2 = io.StringIO()
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
output2.writelines(lines)
print(output2.getvalue())
# Real file writing patterns:
# with open("output.txt", "w") as f:
# f.write("Hello!\n")
# Append mode ('a') — adds to end
# with open("log.txt", "a") as f:
# f.write("New log entry\n")
# Write with print()
# with open("output.txt", "w") as f:
# print("Hello!", file=f)
# Practical: generate a report
report = io.StringIO()
data = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
print("=== Student Report ===", file=report)
for name, score in data:
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(f"{name}: {score} ({grade})", file=report)
print(f"Average: {sum(s for _, s in data)/len(data):.1f}", file=report)
print(report.getvalue())Tip
Tip
Use mode 'a' to append without overwriting existing content. Use 'w' only when you want to start fresh.
Diagram
Loading diagram…
Everything in Python is an object — use type() to check
Common Mistake
Warning
Opening a file with 'w' mode erases ALL existing content immediately. Use 'a' to append or check if file exists first.
Practice Task
Note
(1) Write a list of items to a file. (2) Append new items. (3) Read and verify the contents.