Python Writing Files
Table of Contents + −
In the last lesson you learned Reading Files. You opened a file and pulled the text out of it. Now we go the other way. We put text into a file so it stays around even after your program ends.
🤔 Why Write to a File?
Here is the problem. A normal variable lives only while your program is running. The moment the program stops, that value is gone. So if Alex works out a score, or types a quick note, and you just keep it in a variable, it disappears the second the script finishes.
Writing to a file fixes that. It saves your text onto the disk. So you can open the program again tomorrow and the text is still there.
You do it with two steps. First you open the file in write mode. Then you call write() to put text in.
🧩 The Syntax
You open a file the same way you did for reading. The difference is the second argument. Instead of "r" for read, you pass "w" for write.
This opens a file called note.txt for writing and saves one line into it.
file = open("note.txt", "w")file.write("Remember to drink water.")file.close()Let’s walk through each line.
open("note.txt", "w")opens the file in write mode. If the file does not exist yet, Python creates it for you.file.write(...)puts the text you give it into the file.file.close()saves the changes and closes the file. Always close a file when you are done with it.
After you run this, a file named note.txt sits next to your script. Open it and you will see this.
Output
Remember to drink water.⚠️ “w” Erases Everything First
This is the part people get caught by. So read it slowly. When you open a file with "w", Python empties the whole file before you write a single character. Whatever was in there before is gone.
So this is not “add to the file”. It is “replace the file”.
Say note.txt already had a shopping list in it. Then Alex runs this code.
file = open("note.txt", "w")file.write("Hello!")file.close()The shopping list is now deleted. The file only contains Hello!. There is no undo. So before you use "w" on a file that has something important in it, stop and make sure you really want to wipe it.
Caution
Opening a file in "w" mode erases its contents the moment you open it. This happens even if you never call write(). If you want to keep the old text and add to it, you need append mode. That is the next lesson.
🤔 write() Does Not Add New Lines
Here is a surprise that trips up almost everyone. The write() method does not move to a new line after it finishes. The print() function does that for you. But write() does not add a newline.
So if you call write() three times, all the text lands on one single line, stuck together.
This code writes three names with no newline character between them.
file = open("names.txt", "w")file.write("Alex")file.write("Riya")file.write("Arjun")file.close()Open names.txt and you get one squashed line.
Output
AlexRiyaArjunTo put each name on its own line, you add the newline character \n yourself at the end of each piece of text.
This version adds \n after every name. So each one sits on a new line.
file = open("names.txt", "w")file.write("Alex\n")file.write("Riya\n")file.write("Arjun\n")file.close()Now the file reads like this.
Output
AlexRiyaArjunSo the rule is simple. \n means “start a new line here”. You decide where the lines break.
🧩 A Real Example: Saving a Score
Let’s make it feel real. Say Riya just finished a quiz game. You want to save her score so she can see it later.
This program builds a result message with an f-string and writes it to a file.
name = "Riya"score = 87
file = open("scores.txt", "w")file.write(f"Player: {name}\n")file.write(f"Score: {score}\n")file.write("Result: Passed\n")file.close()
print("Score saved to scores.txt")Reading the code top to bottom.
- We set up
nameandscoreas normal variables. - We open
scores.txtin write mode. - Each
write()line drops one line of text into the file. The\nkeeps them on separate lines. - The f-string lets us mix the variables straight into the sentence.
- We close the file. Then we print a small message so we know it worked.
Your terminal shows this.
Output
Score saved to scores.txtAnd the file scores.txt now holds this.
Output
Player: RiyaScore: 87Result: PassedSee how the score lives in the file now? Close the program, come back next week, open scores.txt, and it is still there.
🧩 Writing Many Lines at Once
Sometimes you have a list of things and you want each one on its own line. You could call write() over and over. But there is a tidier way.
The writelines() method takes a list of strings and writes them one after another. Note the name carefully though. Even though it is called writelines, writelines() still does not add newlines. You add \n yourself.
This code takes a list of tasks and writes each one on its own line.
tasks = ["Buy milk\n", "Call Arjun\n", "Finish report\n"]
file = open("todo.txt", "w")file.writelines(tasks)file.close()The file todo.txt ends up like this.
Output
Buy milkCall ArjunFinish report🛠️ The Safer Way: with open()
There is a cleaner way to write files that you should start using. You open the file with the word with. The big win is that the file closes itself automatically when the block ends. This happens even if something goes wrong partway through.
This does the same job as before. But the file closes on its own.
with open("note.txt", "w") as file: file.write("Saved the safe way.\n")
print("Done, and the file is already closed.")Notice there is no file.close() line. The with block handles that for you the moment the indented part finishes. From here on, prefer this style. It is shorter and you can never forget to close the file.
📋 Read vs Write Modes
Here are the basic modes side by side so you can keep them straight.
| Mode | Meaning | If the file exists |
|---|---|---|
"r" | Read | Reads its contents |
"w" | Write | Erases it, then writes |
"a" | Append | Keeps it, adds to the end |
⚠️ Common Mistakes
A few slips show up again and again when people start writing files.
- Forgetting that
"w"wipes the file first. If the file had something you needed, it is gone now.
# ❌ Avoid: opening an important file in "w" just to add one linefile = open("important_data.txt", "w") # everything already inside is erased here
# ✅ Good: use "a" (append) when you want to keep what is therefile = open("important_data.txt", "a")- Expecting
write()to break lines for you. It does not, so everything runs together.
# ❌ Avoid: no newline, both pieces stick togetherfile.write("Line one")file.write("Line two")
# ✅ Good: add \n yourselffile.write("Line one\n")file.write("Line two\n")- Passing a number straight to
write(). It only accepts text, so convert numbers first.
score = 87
# ❌ Avoid: this raises a TypeErrorfile.write(score)
# ✅ Good: turn the number into a stringfile.write(str(score))- Forgetting to close the file. If you do not close it, your text may not actually be saved. Using
with open()avoids this completely.
✅ Best Practices
Small habits that keep file writing safe and clean.
- Use
with open(...)so the file always closes itself. - Think twice before opening a real file in
"w"mode, because it erases everything first. - Add
\non purpose wherever you want a new line. - Wrap numbers and other values in
str(...)before writing them. - Use f-strings to build clear lines of text from your variables.
🧩 What You’ve Learned
A quick recap of what you can do now.
- ✅ Open a file for writing with
open(filename, "w"). - ✅ Put text into a file with the
write()method. - ✅ Remember that
"w"mode erases the whole file before writing. - ✅ Add
\nyourself to break text onto new lines. - ✅ Write a list of lines with
writelines(). - ✅ Use
with open(...)so the file closes on its own.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What happens to a file when you open it with open("data.txt", "w")?
Why: The "w" mode empties the whole file the moment you open it, so any existing content is lost.
- 2
What does the write() method do at the end of the text you give it?
Why: Unlike print(), write() does not add a newline, so you include \n yourself wherever you want a line break.
- 3
Why does file.write(87) raise an error?
Why: write() only accepts strings, so you must convert numbers first with str(87).
- 4
What is the main advantage of using with open(...) to write a file?
Why: A with block closes the file on its own when the indented code finishes, so you never forget to close it.
🚀 What’s Next?
You now know how to save text. But every time you used "w" it erased the old content first. What if you want to keep what is already there and just add to the end? That is exactly what append mode does.