🎓 A1Learner
🔍

Python Write to Files

Writing a file sends text from a program to disk. The mode chooses between replacing old text and adding new text.

w empties the file first

The second w open wipes the old text. Only the new short text stays.

with open("note.txt", "w") as f:
    f.write("long text here")
with open("note.txt", "w") as f:
    f.write("short")
with open("note.txt", "r") as f:
    print(f.read())

write() counts characters

write() hands back a count. The word hello has five letters.

with open("note.txt", "w") as f:
    count = f.write("hello")
print(count)

a adds at the end

The a mode keeps old text. New text goes after it.

with open("note.txt", "w") as f:
    f.write("first\n")
with open("note.txt", "a") as f:
    f.write("second\n")
with open("note.txt", "r") as f:
    print(f.read(), end="")

Write a list of lines

writelines() writes each string in the list. Each string carries its own newline.

lines = ["one\n", "two\n", "three\n"]
with open("note.txt", "w") as f:
    f.writelines(lines)
with open("note.txt", "r") as f:
    print(f.read(), end="")

Numbers need str() first

A file holds text only. Convert a number with str() before you write it.

score = 95
with open("note.txt", "w") as f:
    f.write(str(score))
with open("note.txt", "r") as f:
    print(f.read())

Example

with open("diary.txt", "w") as f:
    f.write("Day 1: I learned to write files.\n")

with open("diary.txt", "a") as f:
    f.write("Day 2: I appended a new entry.\n")

with open("diary.txt", "r") as f:
    print(f.read(), end="")

Key points

  • Use "w" to write.
  • It creates the file or empties it first.
  • Writing a file stores program text on disk.
  • Use "a" to add new text at the end of the file
  • write() returns the number of characters it wrote
  • Use writelines() to write a list of strings in one call
  • writelines() adds no newlines for you.
  • Add them inside each string.

In this example, the first block opens diary.txt with mode w. It writes the Day 1 entry. The second block opens the file with mode a. It appends the Day 2 entry after the first. The last block reads the whole file back. Both entries print, so the append worked.

Note

Files hold text, not numbers.

Writing a number without str() raises TypeError.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What must you do before writing the number 95 to a file?