Write, Overwrite, Append: How Python Handles File Output
The idea
Reading gets data out of a file. Writing puts data in.
Python gives you two distinct modes for this — and the difference between them matters.
write() — create or overwrite
Mode "w" opens a file for writing. If the file doesn't exist, Python creates it. If it does — it's wiped clean first.
with open("roster.txt", "w", encoding="utf-8") as f:
f.write("Raven\n")
f.write("Wolf\n")
f.write("Ghost\n")
After this runs, roster.txt contains exactly three lines. Whatever was there before is gone.
f.write() doesn't add a newline automatically — you add \n yourself.
Writing multiple lines at once
writelines() takes a list and writes each element — no newlines added automatically:
soldiers = ["Raven\n", "Wolf\n", "Ghost\n"]
with open("roster.txt", "w", encoding="utf-8") as f:
f.writelines(soldiers)
Same result as before. Cleaner when you already have a list.
append() — add without destroying
Mode "a" opens a file and adds to the end. Existing content is untouched.
with open("roster.txt", "a", encoding="utf-8") as f:
f.write("Viper\n")
f.write("Bull\n")
Now roster.txt has five lines — the original three plus two new ones.
If the file doesn't exist, "a" creates it. Same as "w" in that regard.
Writing data from variables
soldiers = ["Raven", "Wolf", "Ghost", "Viper", "Bull"]
with open("roster.txt", "w", encoding="utf-8") as f:
for soldier in soldiers:
f.write(soldier + "\n")
Loop through your data, write each value, add a newline. That's the standard pattern.
Checking what was written
After writing, read the file back to verify:
with open("roster.txt", "r", encoding="utf-8") as f:
print(f.read())
write mode vs append mode — side by side
"w"— starts fresh every time. Use when you want to replace the file completely."a"— adds to what's already there. Use when you want to keep existing data and add more.
Running a script in "w" mode twice produces one file with one set of data.
Running a script in "a" mode twice produces one file with two sets of data.
Heads up!
"w"overwrites silently — there's no confirmation, no warning, no undof.write()requires a string — convert numbers withstr()or f-stringswritelines()does not add newlines — include\nin your strings- The file is created in the same folder as your script if you use just a filename
What you should understand now
"w"creates or overwrites — existing content is gone"a"appends — existing content is preservedf.write(string)writes one string — add\nmanuallyf.writelines(list)writes a list of strings — add\nin the strings- Loop over your data and write each item for the most common pattern