Writing Files
in Python
Learn how to create, write, and append text to files using Python's built-in file handling: master the difference between overwrite and append modes.
What Is File Writing?
Programs often need to save data permanently: a high-score list, a log of events, or a report. When your program ends, all variables vanish from memory. Writing to a file puts that data on disk so it survives after the program stops.
The open() Function
To write to a file, you call open() with two arguments: the filename and the mode. The mode tells Python what you intend to do with the file.
The File Lifecycle
Write Mode: "w"
Opening a file with "w" means overwrite. If the file already exists, its contents are erased completely before your new data is written. If it doesn't exist, Python creates it.
Append Mode: "a"
Opening a file with "a" means append. New data is added to the end of whatever already exists. Nothing is erased. If the file doesn't exist, Python creates it (just like "w").
"w" vs "a": The Key Difference
The with Statement
The with statement is the recommended way to work with files in Python. It automatically closes the file when the block ends, even if an error occurs.
f.write("data")
f.close() # easy to forget!
f.write("data")
# auto-closed!
How to Write a File
Example 1: Creating a File
Example 2: Appending to a Log
Example 3: Writing with a Loop
Bonus: writelines()
If you have a list of strings ready to go, you can write them all at once with writelines() instead of looping over write().
Common Mistakes
Mode Comparison Table
| "w" (Write) | "a" (Append) | "r" (Read) | |
|---|---|---|---|
| Creates file if missing? | Yes | Yes | No (error) |
| Erases existing content? | Yes | No | N/A |
| Writes to? | Start of file | End of file | Cannot write |
| Best for? | Fresh output | Logs, history | Reading input |
Question 1 of 5
What happens when you open an existing file with mode "w"?
Question 2 of 5
Which mode should you use to add new lines to a log file without losing old entries?
Question 3 of 5
What is the main advantage of using the with statement when writing files?
Question 4 of 5
What does the following code produce in output.txt?
Code:
with open("output.txt", "w") as f:
f.write("Hello")
f.write("World")
Question 5 of 5
What happens if you call f.write(42) without converting to a string?