Write text with mode "w"

with open("notes.txt", "w") as f:
    f.write("First line
")
    f.write("Second line
")

Mode "w" replaces any existing contents, so use it when you want a fresh file. Note that write does not add a newline for you — include yourself.

Append instead of overwrite with mode "a"

with open("notes.txt", "a") as f:
    f.write("Added at the end
")

Mode "a" keeps the existing text and adds your new content to the end of the file, which is perfect for logs.

Write a list of lines with writelines()

lines = ["apple
", "banana
", "cherry
"]
with open("fruit.txt", "w") as f:
    f.writelines(lines)

writelines writes every string in the list back to back, so remember to include the newline characters yourself.

Which method should you use?

  • Mode "w" — when you want to create or replace a file.
  • Mode "a" — when you want to add to an existing file.
  • print(..., file=f) — a handy alternative that adds newlines automatically.
  • Common mistake: opening with "w" when you meant "a" and silently wiping your data.

Frequently asked questions

Why does my file write nothing?

Usually because the file was never closed. Use a with block, which flushes and closes automatically, instead of calling open on its own.

How do I write non-text data like numbers?

Convert values to strings first, for example f.write(str(42)), since write only accepts text in text mode.

Ready to practise file handling end to end? Our free Python course walks you through it.