Python Basics — Writing Files
Writing Files
Writing data to files lets you save program output, create reports, store configuration, and persist user data.
Write Mode ("w")
Write mode creates a new file or overwrites an existing one:
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.write("This is line 2.\n")
The file now contains:
Hello, World!
This is line 2.
Warning:
"w"mode erases all existing content. Be careful not to lose data!
Append Mode ("a")
Append mode adds content to the end of an existing file (or creates it if it doesn’t exist):
with open("log.txt", "a") as f:
f.write("2025-03-03 10:00 — Server started\n")
# Later...
with open("log.txt", "a") as f:
f.write("2025-03-03 10:05 — User logged in\n")
The file accumulates entries:
2025-03-03 10:00 — Server started
2025-03-03 10:05 — User logged in
write() and writelines()
write() — Write a Single String
with open("output.txt", "w") as f:
f.write("Line 1\n")
f.write("Line 2\n")
writelines() — Write a List of Strings
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
Note:
writelines()does NOT add newlines automatically — you must include\nin each string.
Creating New Files
Exclusive Create Mode ("x")
Creates a file only if it doesn’t already exist:
try:
with open("newfile.txt", "x") as f:
f.write("This is a brand new file!\n")
print("File created successfully!")
except FileExistsError:
print("File already exists — not overwriting.")
Binary Mode ("wb")
For non-text files (images, PDFs, etc.):
# Copy a binary file
with open("photo.jpg", "rb") as source:
data = source.read()
with open("photo_copy.jpg", "wb") as dest:
dest.write(data)
print() to a File
You can use print() with the file parameter:
with open("output.txt", "w") as f:
print("Name: Alice", file=f)
print("Age:", 30, file=f)
print(f"Score: {95.5:.1f}", file=f)
Contents:
Name: Alice
Age: 30
Score: 95.5
This is handy because print() automatically adds newlines.
Checking if File Exists Before Writing
from pathlib import Path
file_path = Path("important_data.txt")
if file_path.exists():
print("File exists — using append mode")
mode = "a"
else:
print("File doesn't exist — creating new")
mode = "w"
with open(file_path, mode) as f:
f.write("New data entry\n")
Writing with pathlib
from pathlib import Path
# Write text
Path("output.txt").write_text("Hello from pathlib!\n", encoding="utf-8")
# Read it back
content = Path("output.txt").read_text(encoding="utf-8")
print(content) # Hello from pathlib!
write_text()always overwrites. There’s no append mode with this method.
Practical Example: Writing a Report
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78},
{"name": "Diana", "score": 95},
]
with open("report.txt", "w", encoding="utf-8") as f:
f.write("=" * 30 + "\n")
f.write(" Student Report Card\n")
f.write("=" * 30 + "\n\n")
for student in students:
grade = "A" if student["score"] >= 90 else ("B" if student["score"] >= 80 else "C")
f.write(f" {student['name']:<10} {student['score']} ({grade})\n")
avg = sum(s["score"] for s in students) / len(students)
f.write(f"\n Average: {avg:.1f}\n")
f.write("=" * 30 + "\n")
# Verify
with open("report.txt", "r") as f:
print(f.read())
Output:
==============================
Student Report Card
==============================
Alice 85 (B)
Bob 92 (A)
Charlie 78 (C)
Diana 95 (A)
Average: 87.5
==============================
Summary
| Mode | Action | Existing File | No File |
|---|---|---|---|
"w" |
Write (overwrite) | Erases content | Creates new |
"a" |
Append | Adds to end | Creates new |
"x" |
Exclusive create | FileExistsError | Creates new |
"wb" |
Write binary | Erases content | Creates new |
write()writes a string;writelines()writes a list of strings- Neither adds newlines automatically — include
\nyourself - Use
print(..., file=f)for convenient formatted output - Use
pathlib.Path.write_text()for quick one-line writes - Always specify
encoding="utf-8"for text files
Next up: Context Managers →