Lesson 3 of 5 · Errors and Files · 2 min read · Updated

Writing files

Saving text to a file so it outlives the program, and the with statement that closes it for you.

Variables vanish when the program ends. Anything worth keeping must go into a file.

python
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Buy milk\n")
    f.write("Call Ravi\n")

with open("notes.txt", "a", encoding="utf-8") as f:
    f.write("Pay fees\n")

with open("notes.txt", encoding="utf-8") as f:
    print(f.read())
Output
Buy milk
Call Ravi
Pay fees
  • with open(...) as f: opens the file and closes it automatically when the block ends — even if an error happens.
  • write() does not add a new line; put \n in yourself.
  • Always pass encoding="utf-8", or Tamil text may save as garbage on Windows.

File modes

  • "r" — read (the default). The file must exist.
  • "w" — write. Creates the file, or empties it if it exists.
  • "a" — append. Adds to the end, keeping what is there.
  • "x" — create. Fails if the file already exists, so nothing is overwritten.

Warning

Opening an existing file with "w" deletes its contents immediately, before you write a single character. Use "a" to add to a file.

Writing rows of data

python
marks = {"Priya": 87, "Arun": 73}
with open("marks.csv", "w", encoding="utf-8") as f:
    f.write("name,marks\n")
    for name, m in marks.items():
        f.write(f"{name},{m}\n")

with open("marks.csv", encoding="utf-8") as f:
    print(f.read())
Output
name,marks
Priya,87
Arun,73

Which mode adds to the end of a file without erasing it?

Try this now

  1. Write a diary program that asks for one line and appends it to diary.txt each time it runs.
  2. Write the multiplication table of 7 into a file, one line per row.

Create a free account to save your progress, or sign in.