Python for beginners · Lesson 14 of 15

Reading and writing files

Open text files with open(), read them whole or line by line, write and append text, and let the with statement close files for you.

About 16 minutes · code runs in your browser, nothing to install

Variables disappear when a program ends. To keep data, programs save it in files. In this lesson the example files are created for you before each code box runs, so you can read them right away.

Reading a whole file

open() opens a file and gives you a file object. The with statement statement closes the file automatically when its block ends, even if an error happens. encoding="utf-8" makes sure letters like é or ü are read correctly on every computer. read() returns the whole file as one string.

Pythoneditable
with open("poem.txt", encoding="utf-8") as f:
    text = f.read()
print(text)
Output
Roses are red,
Violets are blue,
Python is fun,
And so are you.

Line by line

Looping over a file object gives you one line at a time. Each line still ends with an invisible new-line character \n, so use strip() to remove it. readlines() reads all lines into a list instead.

Pythoneditable
with open("poem.txt", encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.strip())

with open("poem.txt", encoding="utf-8") as f:
    lines = f.readlines()
print(lines)
print(len(lines), "lines")
Output
1 Roses are red,
2 Violets are blue,
3 Python is fun,
4 And so are you.
['Roses are red,\n', 'Violets are blue,\n', 'Python is fun,\n', 'And so are you.\n']
4 lines

Writing and appending

Give open() a second argument, the mode: "w" writes a new file (and empties it first if it already exists), "a" appends to the end. write() does not add a new line by itself, so put \n at the end of each line.

Pythoneditable
with open("todo.txt", "w", encoding="utf-8") as f:
    f.write("buy milk\n")
    f.write("call Sam\n")

with open("todo.txt", "a", encoding="utf-8") as f:
    f.write("water plants\n")

with open("todo.txt", encoding="utf-8") as f:
    print(f.read())
Output
buy milk
call Sam
water plants
Watch out: Mode "w" wipes the file before writing. If you want to keep what is already there, use "a".

Reading data from a file

Text files often hold data, one record per line, with commas between the fields. Split each line, convert the numbers, and you can calculate with them.

Pythoneditable
total = 0
count = 0
with open("scores.txt", encoding="utf-8") as f:
    for line in f:
        name, score = line.strip().split(",")
        print(f"{name}: {score}")
        total += int(score)
        count += 1
print("Average:", round(total / count, 1))
Output
Lena: 82
Omar: 95
Yuki: 78
Average: 85.0

Opening a file that does not exist raises a FileNotFoundError, which you can catch like any other error.

Pythoneditable
try:
    with open("missing.txt", encoding="utf-8") as f:
        print(f.read())
except FileNotFoundError:
    print("Could not find missing.txt")
Output
Could not find missing.txt

✎ Exercise

shopping.txt has one item per line, plus an empty line. Read the items into a list (skipping empty lines), print how many there are followed by the word items, then write them as a numbered list (1. apples, 2. bread, ...) into list.txt and print that file.

Hint: strip() each line and only append it when it is not an empty string. Write with mode "w" and end every line with \n.

Your codewrite your answer, then Run
items = []
# your code here

Expected output:

4 items
1. apples
2. bread
3. milk
4. cheese
Show a solution
Solutioneditable
items = []
with open("shopping.txt", encoding="utf-8") as f:
    for line in f:
        item = line.strip()
        if item != "":
            items.append(item)
print(len(items), "items")

with open("list.txt", "w", encoding="utf-8") as out:
    for number, item in enumerate(items, start=1):
        out.write(f"{number}. {item}\n")

with open("list.txt", encoding="utf-8") as f:
    print(f.read())
Output
4 items
1. apples
2. bread
3. milk
4. cheese

Check yourself

1. What does mode "w" do to an existing file?

2. Why use with open(...) as f:?

3. Why do we call strip() on lines read from a file?

Spotted a mistake on this page? Tell us