Writing Data to Files
Overview
Python makes it simple to store data by writing to files. You'll use write() and writelines() to output information and learn how overwriting, appending, and formatting affect stored results, creating persistent data storage solutions.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Writing to files: Use
write()to save data to files. - Writing multiple lines: Use
writelines()to write lists of strings. - Write vs append: Understand the difference between overwriting and adding to files.
- Formatting output: Learn how to format data before writing it to files.
- Common patterns: Master the most common ways to save data.
The write() Method
The write() method writes a string to a file. You can only write to files opened in write ('w') or append ('a') mode.
file = open("output.txt", "w")
file.write("Hello, World!")
file.close()
Important: write() only accepts strings. If you want to write numbers or other types, convert them to strings first using str().
file = open("data.txt", "w")
file.write("Text: Hello\n")
file.write("Number: " + str(42) + "\n")
file.write("Float: " + str(3.14) + "\n")
file.close()
Write Mode vs Append Mode
Understanding the difference between 'w' and 'a' modes is crucial for file writing:
Write Mode ('w')
Overwrites the entire file. If the file exists, all its content is deleted first.
file = open("log.txt", "w")
file.write("New content")
file.close()
# File now contains ONLY "New content"
Append Mode ('a')
Adds to the end of the file. Existing content stays intact.
file = open("log.txt", "a")
file.write("More content")
file.close()
# File now contains old content + "More content"
When to Use Each
- Use 'w': When you want to create a new file or replace all existing content
- Use 'a': When you want to add to an existing file (like logging or keeping a history)
Writing Multiple Lines
To write multiple lines, you need to include newline characters (\n) in your strings.
file = open("lines.txt", "w")
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")
file.close()
Remember the Newline
Without \n, everything would be on one line. Always add \n at the end of each line you write.
name = "Alice"
score = 95
file = open("scores.txt", "w")
file.write(f"{name}: {score}\n")
file.close()
The writelines() Method
The writelines() method writes a list of strings to a file. It's useful when you have multiple lines stored in a list.
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file = open("output.txt", "w")
file.writelines(lines)
file.close()
Important: writelines() doesn't add newlines automatically. You must include \n in each string if you want separate lines.
names = ["Alice", "Bob", "Charlie"]
file = open("names.txt", "w")
for name in names:
file.write(name + "\n")
file.close()
# Or using writelines:
lines = [name + "\n" for name in names]
file = open("names.txt", "w")
file.writelines(lines)
file.close()
Practice: Writing to Files
Try It YourselfTry writing different types of data to a file:
What happened? You simulated writing multiple lines to a file. In a real program, you would use file.write() for each line.
Common Writing Patterns
Here are the most common patterns for writing to files:
Writing Formatted Data
Use f-strings or string formatting to create readable output.
with open("report.txt", "w") as file:
file.write(f"Total: {total}\n")
file.write(f"Average: {average:.2f}\n")
file.write(f"Count: {count}\n")
Writing from a Loop
Process data and write results line by line.
with open("output.txt", "w") as file:
for item in data:
file.write(f"{item}\n")
Appending Logs
Use append mode to keep a history of events.
from datetime import datetime
with open("log.txt", "a") as file:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
file.write(f"{timestamp}: {event}\n")
Writing Structured Data
Write data in a structured format (like CSV).
students = [("Alice", 95), ("Bob", 87)]
with open("grades.txt", "w") as file:
file.write("Name,Score\n")
for name, score in students:
file.write(f"{name},{score}\n")
Important Notes About Writing
Keep these important points in mind when writing to files:
Writing Considerations
- Newlines: Always add
\nat the end of each line you write - String conversion:
write()only accepts strings - convert numbers usingstr() - Mode matters: 'w' overwrites, 'a' appends - choose carefully!
- Buffering: Data might not be written immediately - closing the file ensures it's saved
- File existence: 'w' and 'a' modes create the file if it doesn't exist
name = "Alice"
age = 25
score = 95.5
is_active = True
with open("data.txt", "w") as file:
file.write(f"Name: {name}\n")
file.write(f"Age: {str(age)}\n") # Convert to string
file.write(f"Score: {str(score)}\n")
file.write(f"Active: {str(is_active)}\n")
# Or use f-strings (they convert automatically)
with open("data2.txt", "w") as file:
file.write(f"Name: {name}\n")
file.write(f"Age: {age}\n") # f-string converts automatically
file.write(f"Score: {score}\n")
file.write(f"Active: {is_active}\n")
Summary
In this lesson, you learned:
write(): Writes a string to a file - remember to add\nfor new lineswritelines(): Writes a list of strings to a file- Write mode ('w'): Overwrites existing content - use to create new files
- Append mode ('a'): Adds to end of file - use for logs and history
- Formatting: Use f-strings to format data before writing
Remember
Always close files after writing to ensure your data is saved! And don't forget the \n for newlines.
End-of-Lesson Exercises
Think about these questions to reinforce what you've learned:
Exercise 1: Write vs Append
When would you use write mode vs append mode? Give a real-world example for each.
Exercise 2: Writing Data
Write pseudocode for saving a list of student names and scores to a file, with each student on a separate line.