Working with Files - Writing
Learn to write and save data to files in Python
Working with Files - Writing
Why Write Files?
Writing files lets your program save data permanently. When the program stops, the data in variables is lost, but files keep the data for later.
Common uses:
- Save user preferences
- Export results
- Create logs
- Save game progress
- Generate reports
Opening a File for Writing
To write to a file, open it with "w" mode.
with open("output.txt", "w") as file:
file.write("Hello, World!")What this does: Creates output.txt (or overwrites it if it exists) and writes "Hello, World!" to it.
Important: Mode "w" erases existing content. Be careful!
File Opening Modes
Python has different modes for different needs:
-
"w" - Write mode
- Creates new file or overwrites existing file
- Deletes all previous content
- Use when starting fresh
-
"a" - Append mode
- Creates new file if it doesn't exist
- Adds to end of existing file
- Keeps previous content
- Use when adding to existing data
-
"r" - Read mode
- Only for reading (covered in previous lesson)
- Cannot write
- File must exist
Writing Single Line
with open("data.txt", "w") as file:
file.write("This is a line of text")What happens: Creates data.txt with one line of text.
Note: write() doesn't add a newline automatically. The file will have exactly what you wrote.
Writing Multiple Lines
Adding Newlines Manually
with open("data.txt", "w") as file:
file.write("First line\n")
file.write("Second line\n")
file.write("Third line\n")What \n does: Creates a new line. Without it, everything runs together.
Using writelines()
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("data.txt", "w") as file:
file.writelines(lines)What this does: Writes all lines from the list to the file.
Important: writelines() doesn't add newlines. You must include \n in each string.
Appending to Files
Append mode adds content to the end without deleting what's already there.
with open("log.txt", "a") as file:
file.write("New log entry\n")What happens: If log.txt exists, the new text is added at the end. If it doesn't exist, a new file is created.
Example showing the difference:
with open("test.txt", "w") as file:
file.write("First write\n")
with open("test.txt", "w") as file:
file.write("Second write\n")Result: File only contains "Second write" (first was erased)
with open("test.txt", "w") as file:
file.write("First write\n")
with open("test.txt", "a") as file:
file.write("Second write\n")Result: File contains both lines (second was appended)
Writing Numbers
The write() method only accepts strings, not numbers.
Wrong way:
number = 42
with open("data.txt", "w") as file:
file.write(number) # Error!Right way:
number = 42
with open("data.txt", "w") as file:
file.write(str(number))What happens: str() converts the number to text before writing.
Writing Lists to Files
Writing String List
names = ["John", "Sarah", "Mike"]
with open("names.txt", "w") as file:
for name in names:
file.write(name + "\n")Result (names.txt):
John
Sarah
Mike
Writing Number List
scores = [85, 92, 78, 95]
with open("scores.txt", "w") as file:
for score in scores:
file.write(str(score) + "\n")Result (scores.txt):
85
92
78
95
Writing CSV-like Data
You can create files with comma-separated values.
students = [
["John", "25", "A"],
["Sarah", "22", "B"],
["Mike", "23", "A"]
]
with open("students.csv", "w") as file:
for student in students:
line = ",".join(student)
file.write(line + "\n")Result (students.csv):
John,25,A
Sarah,22,B
Mike,23,A
What join() does: Combines list items into one string with commas between them.
Handling Write Errors
Writing can fail (disk full, no permission). Always handle errors.
try:
with open("output.txt", "w") as file:
file.write("Some data")
print("File written successfully")
except IOError:
print("Error writing file")What this does: If writing fails, shows error message instead of crashing.
Creating Files in Specific Folders
You can specify a path when creating files.
with open("data/output.txt", "w") as file:
file.write("Data in folder")Important: The folder (data) must exist first. Python won't create folders automatically.
Practice Example
The scenario: You're creating a simple grade tracking system that saves student records to a file.
students = {
"John": {"math": 85, "science": 90},
"Sarah": {"math": 92, "science": 88},
"Mike": {"math": 78, "science": 85}
}
try:
with open("grades.txt", "w") as file:
file.write("Student Grade Report\n")
file.write("=" * 30 + "\n\n")
for name, grades in students.items():
file.write("Student: " + name + "\n")
file.write(" Math: " + str(grades["math"]) + "\n")
file.write(" Science: " + str(grades["science"]) + "\n")
avg = (grades["math"] + grades["science"]) / 2
file.write(" Average: " + str(avg) + "\n\n")
file.write("=" * 30 + "\n")
file.write("Total students: " + str(len(students)) + "\n")
print("Report saved to grades.txt")
except IOError:
print("Error saving report")What this creates (grades.txt):
Student Grade Report
==============================
Student: John
Math: 85
Science: 90
Average: 87.5
Student: Sarah
Math: 92
Science: 88
Average: 90.0
Student: Mike
Math: 78
Science: 85
Average: 81.5
==============================
Total students: 3
Updating Existing Files
To update a file, you need to read it first, modify the data, then write it back.
with open("data.txt", "r") as file:
lines = file.readlines()
lines.append("New line\n")
with open("data.txt", "w") as file:
file.writelines(lines)What this does:
- Reads all existing lines
- Adds a new line to the list
- Writes everything back to the file
Key Points to Remember
Use "w" mode to create or overwrite files, "a" mode to append without deleting existing content.
write() method only accepts strings. Convert numbers using str() before writing.
write() doesn't add newlines automatically. Include \n when you want new lines.
writelines() writes a list of strings but doesn't add newlines between them.
Always use with statement so files close properly and changes are saved.
Common Mistakes
Mistake 1: Forgetting to convert numbers
file.write(42) # Error!
file.write(str(42)) # CorrectMistake 2: Using "w" when you want to append
with open("log.txt", "w") as file: # This erases everything!
file.write("New entry")Use "a" instead:
with open("log.txt", "a") as file:
file.write("New entry")Mistake 3: Forgetting newlines
file.write("Line 1")
file.write("Line 2") # Both on same line!Fix:
file.write("Line 1\n")
file.write("Line 2\n")Mistake 4: Trying to create file in non-existent folder
with open("data/output.txt", "w") as file: # Error if data folder doesn't exist!What's Next?
You now know how to read and write files. Next, you'll learn about file paths and directory operations - navigating folders, checking if files exist, and managing file systems.