ShareYourGroupShareYourGroupPython

Lesson 18 of 21 · about 7 minutes with the exercises

Reading and writing files

Variables live in memory and vanish when the program stops. To keep information, a program writes it to a file. Next time it can read the file back. This lesson covers plain text files, which are all you need for notes, logs and simple tables.

Writing a file

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Buy milk\n")
    f.write("Pay the electricity bill\n")
print("Saved")

Output

Saved

Reading the first line piece by piece:

write does not add a new line by itself as print does. You add \n where a line should end.

The modes

ModeMeaningIf the file existsIf it does not
"r"readopens iterror
"w"writeempties it firstcreates it
"a"appendadds at the endcreates it

Take care with "w". One wrong letter and a file full of data becomes an empty one.

Reading a whole file

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Buy milk\nPay the electricity bill\n")

with open("notes.txt", "r", encoding="utf-8") as f:
    text = f.read()
print(text)
print(len(text), "characters")

Output

Buy milk
Pay the electricity bill

34 characters

read returns the entire file as one string. That is fine for small files.

Reading line by line

Looping over the file gives one line at a time. Each line still has its \n at the end, so strip it.

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Buy milk\nPay the electricity bill\nCall the plumber\n")

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

Output

1 Buy milk
2 Pay the electricity bill
3 Call the plumber

The mode is left out here because "r" is the default. To get all the lines as a list in one go, use f.read().splitlines().

Adding to a file

Mode "a" keeps what is there and writes after it. It is the right mode for a diary or a log.

with open("log.txt", "w", encoding="utf-8") as f:
    f.write("Monday: 40 minutes\n")
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("Tuesday: 55 minutes\n")
with open("log.txt", encoding="utf-8") as f:
    print(f.read())

Output

Monday: 40 minutes
Tuesday: 55 minutes

Writing with print

print can send its output to a file. This saves you from joining strings and adding \n by hand.

with open("table.txt", "w", encoding="utf-8") as f:
    for i in range(1, 4):
        print(f"7 x {i} = {7 * i}", file=f)
with open("table.txt", encoding="utf-8") as f:
    print(f.read())

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21

Numbers in files

A text file holds text. Convert numbers with str when writing, or use an f-string, and convert back with int or float when reading.

scores = [78, 91, 66]
with open("scores.txt", "w", encoding="utf-8") as f:
    for s in scores:
        f.write(f"{s}\n")

total = 0
with open("scores.txt", encoding="utf-8") as f:
    for line in f:
        total += int(line)
print(total)

Output

235

Simple tables: CSV

A CSV file stores a table as text, one row per line, with commas between the columns. Spreadsheet programs open and save it. Python has a csv module that deals with the awkward cases, such as a comma inside a value.

import csv

rows = [["name", "marks"], ["Asha", 78], ["Ravi", 91]]
with open("marks.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows(rows)

with open("marks.csv", newline="", encoding="utf-8") as f:
    for record in csv.DictReader(f):
        print(record["name"], int(record["marks"]) + 5)

Output

Asha 83
Ravi 96

DictReader uses the first row as headings and hands you each later row as a dictionary. The values arrive as strings, so the marks are converted with int.

When the file is not there

Opening a missing file for reading stops the program.

with open("missing.txt", encoding="utf-8") as f:
    print(f.read())

What Python says

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    with open("missing.txt", encoding="utf-8") as f:
         ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'

The next lesson shows how to catch this error and carry on. See also the FileNotFoundError page, which explains folders and paths.

Where is my file?

A bare name such as "notes.txt" means "in the current folder", which is usually the folder your program was started from. If your program cannot find a file you can see, the two are probably in different folders. Keeping the program and its data files together in one folder avoids most trouble.

Try it yourself

Exercise 1. Write the names of three friends to a file called friends.txt, one per line. Then read the file and print how many lines it has.

Show one answer
with open("friends.txt", "w", encoding="utf-8") as f:
    f.write("Asha\nRavi\nMeena\n")
with open("friends.txt", encoding="utf-8") as f:
    print(len(f.read().splitlines()))

Output

3

Exercise 2. Write the numbers 1 to 5 to a file, one per line. Read them back and print their sum.

Show one answer
with open("numbers.txt", "w", encoding="utf-8") as f:
    for n in range(1, 6):
        print(n, file=f)
with open("numbers.txt", encoding="utf-8") as f:
    print(sum(int(line) for line in f))

Output

15

Exercise 3. Create a file with one line, then append a second line, then print the file in capital letters.

Show one answer
with open("shout.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")
with open("shout.txt", "a", encoding="utf-8") as f:
    f.write("second line\n")
with open("shout.txt", encoding="utf-8") as f:
    print(f.read().upper())

Output

FIRST LINE
SECOND LINE

Examples on this page were run with Python 3.14 on 12 November 2026. The output shown is the real output.

This is an independent learning site. It is not connected with or approved by the Python Software Foundation. "Python" is a trademark of the Python Software Foundation and is used here only to name the language.