runtime
91 / 250
lesson 91 Files & Directories · intermediate

Read and write a text file

A program forgets everything when it stops. A file keeps text between runs: open it, write or read, and close it, always saying which encoding the text uses.

You'll be able to
  • Write text to a file with open(path, "w", encoding="utf-8"), remembering that write adds no newline
  • Read a whole file into one string and split it into lines with splitlines()
  • Recognise FileNotFoundError and why every open names encoding="utf-8"
The idea

Every value you've stored so far lives in memory and disappears when the program ends. A file keeps text on disk: a shift note for the next person, a log of what happened, an export another program reads.

open(path, mode, encoding=...) connects your program to a file and gives back a file object. Mode "w" opens it for writing (creating it, or emptying it if it exists); leaving the mode out means "r", reading. write(text) stores text, read() returns everything in the file as one string, and close() finishes with the file so the text is saved and the file is released.

encoding="utf-8" says how characters become bytes on disk. Without it, Python uses the computer's preferred encoding, which is not UTF-8 everywhere (many Windows machines use cp1252), so the same program could read the same file differently. Name it every time.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Write a shift note, then read it back
note = open("shift_note.txt", "w", encoding="utf-8")
note.write("Till 2 short by 5.00\n")
note.write("Fridge 3 at 7 C\n")
note.close()

note = open("shift_note.txt", encoding="utf-8")
text = note.read()
note.close()
print(repr(text))
print(text.splitlines())

Reading a file that isn't there is the most common file error. Python stops with FileNotFoundError and names the path, which is usually a typo or the wrong folder.

example-2.py · A file that doesn't exist
handover = open("handover.txt", encoding="utf-8")
print(handover.read())

In a real program the path is a parameter, so the same function works on any file. This one totals the refund amounts in a file with one amount per line. The first lines of the example only create a sample file, because every run here starts in an empty folder; in practice the file comes from somewhere else.

example-3.py · Total the refunds in a file
def file_total(path):
    source = open(path, encoding="utf-8")
    text = source.read()
    source.close()
    total = 0
    for line in text.splitlines():
        if line.strip() != "":
            total += float(line)
    return total

sample = open("refunds.txt", "w", encoding="utf-8")
sample.write("12.93\n71.14\n\n57.34\n")
sample.close()
print(file_total("refunds.txt"))

When to use it: whenever data has to outlive one run or come from another program. Reading the whole text with read() is fine for small files like notes and settings; the next lessons add a safer way to close files and a way to read big ones a line at a time. Mistakes to avoid: forgetting the \n when writing lines, leaving out encoding="utf-8", and splitting with split("\n"), which leaves an empty string after the last newline (the concept check runs it).

Review
  • open(path, "w", encoding="utf-8") creates or empties a file for writing; leave the mode out to read.
  • write stores exactly what you give it, newlines included only if you write them.
  • read() returns the whole file as one string; splitlines() cuts it into lines without the \n.
  • Next: choose between starting a file fresh and adding to its end.

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Read and write a text file — Files & Directories · Runtime