Reading and Writing Text Files for Beginners: Programming Fundamentals (13)
Learn how programs save data in text files: open, read, write, append and close a file in Python, plus how to design a simple file format.
A file is a named piece of storage on a disk. Programs use files to keep data after they stop running. When your program writes its data to a file, it can read that data back the next time it starts.
After this lesson, you can save data from a program to a text file, read it back, and add to it without losing what was there. You will also know how to choose a simple format for your data.
In this lesson you will:
- Learn why programs need files, and the difference between text files and binary files.
- Open a file in the right mode: read, write or append.
- Write lines to a file and read them back.
- Handle the most common file error.
- Read numbers from one file, sort them, and save them in another file.
It takes about 40 minutes. You need Python 3 on your computer to run the file examples.
Why programs forget
Look back at every program in this series. When it ends, everything it knew is gone. The next time it runs, it starts from zero, and you have to type the values again with Read or input.
The reason is where variables live. Variables live in memory (RAM), and the operating system clears that memory when the program ends. A disk keeps its data when the program ends, and even when the computer turns off. Saving data on a disk so it survives is called persistence. A file is the simplest way to get it.
Two boxes, memory and disk. Step 1: the program runs and keeps the scores Ana 120, Luis 95 and Sofia 140 in variables in memory. Step 2: it writes them to scores.txt on the disk. Step 3: the program ends and its memory is cleared, but the file stays on the disk. Step 4: the program runs again with empty memory and reads the scores back from the file.
The program ends. The operating system clears its memory, but the file stays on the disk.
This is still true when an AI writes your code. Almost every real program saves something: settings, logs, game progress, a list of users. Bugs around files are common and easy to miss. A program that opens a file in the wrong mode can erase months of data on its first run. You need to read file code carefully, whoever wrote it.
StepCode and files
StepCode has no instructions for files. It runs in your browser, and it only reads from the keyboard and writes to the screen. So this lesson teaches files with Python, the language the course used for this unit. You will see Python in normal code blocks, and you run it on your computer.
The logic around files still runs in StepCode. Sorting the numbers, or turning an array into a line of text, does not need a file. Those parts appear as live editors, like in every other lesson.
Text and binary files
There are two kinds of files.
- Text files hold characters that people can read. You can open them in Notepad on Windows or TextEdit on macOS. Each character is stored with a code, such as ASCII or Unicode, as you saw in Strings.
- Binary files hold bytes that only make sense to a specific program. Images, audio, video and executable programs are binary files.
This lesson only uses text files. A text file looks like this:
This is a text file.
It holds plain text that people can read.
Lines end with a character
A text file is one long sequence of characters. A special character marks the end of each line. It is called a line break or newline. In Python, you write it as \n.
Operating systems store it in different ways. Linux and macOS use one character, LF (Line Feed, code 10). Windows uses two, CR and LF (Carriage Return and Line Feed, codes 13 and 10), written \r\n. Python converts them for you when you open a file in text mode, so \n works everywhere.
Open, use, close
Working with a file always has three steps. You open it, you read or write, and you close it.
To open a file in Python, use open(name, mode). The mode is a short text that says what you plan to do. These are the modes from the course notes:
| Mode | Name | What it does |
|---|---|---|
"r" |
Read | Opens a file that exists, to read it. If the file does not exist, you get an error. |
"w" |
Write | Creates a new file to write. If the file exists, it erases everything in it first. |
"a" |
Append | Opens a file to add text at the end. If the file does not exist, it creates it. |
"x" |
Create | Creates a new file to write. If the file already exists, you get an error. |
"r+", "w+", "a+" |
Plus | The same as above, but you can read and write. |
"b" |
Binary | Added to another mode, like "rb", for binary files such as images. |
scores.txt has three lines: Ana 120, Luis 95 and Sofia 140. Opened with "r", the program gets the three lines and the file stays the same. Opened with "w" to write Mateo 130, the old lines are erased and only Mateo 130 is left. Opened with "a", the old lines stay and Mateo 130 is added at the end. Opened with "x", Python stops with FileExistsError because the file exists. If the file does not exist, "r" stops with FileNotFoundError, and "w", "a" and "x" create it with the line Mateo 130.
Write mode erased the 3 old lines first. Only the new line is left.
These are the methods you use on an open file:
| Method | What it does | Gives back |
|---|---|---|
file.write(text) |
Writes the text | Nothing |
file.writelines(list) |
Writes every text in a list | Nothing |
file.read() |
Reads the whole file | One string |
file.readline() |
Reads the next line | One string |
file.readlines() |
Reads every line | A list of strings |
file.close() |
Closes the file | Nothing |
You must always close a file when you finish. Closing makes sure every byte reaches the disk, and it frees the file for other programs. In class, we used the with keyword instead of calling close(). Python closes the file for you when the with block ends, even if something goes wrong inside it. This lesson uses with in every example.
Save and load scores
In this practice, you build a small score board. It saves player scores in scores.txt, reads them back, and adds new ones. Create a new folder, and save each program in it.
1. Write a file with “w”
Save this as write_scores.py. It opens scores.txt in write mode and writes one score per line. Notice the "\n" at the end of each line.
scores = ["Ana 120", "Luis 95", "Sofia 140"]
with open("scores.txt", "w") as file:
for line in scores:
file.write(line + "\n")
print("Saved", len(scores), "scores")
Run it with python3 write_scores.py. You should see:
Saved 3 scores
Open scores.txt in a text editor. It contains:
Ana 120
Luis 95
Sofia 140
Run the program again. The file still has three lines, not six. Write mode erased the old lines before it wrote the new ones.
2. Read the file with “r”
Save this as read_scores.py. readlines() gives you a list with one string per line. Each string still ends with "\n", so strip() removes it. Then split(" ") cuts the line at the space into a name and a number.
with open("scores.txt", "r") as file:
lines = file.readlines()
print("The file has", len(lines), "lines")
for line in lines:
name, points = line.strip().split(" ")
print(name, "has", int(points), "points")
Run it with python3 read_scores.py. You should see:
The file has 3 lines
Ana has 120 points
Luis has 95 points
Sofia has 140 points
Everything you read from a text file is text. The score "120" is a string until int() turns it into a number. It is the same trap as the "34" bug in Programming languages.
To see where each line comes from, picture the file as one long row of characters. readline() reads up to the next newline and keeps it. readlines() repeats that until the file ends.
The file scores.txt is one row of characters: Ana 120, a newline, Luis 95, a newline, Sofia 140, a newline. The first call to readline() reads up to and including the first newline and gives back "Ana 120\n". strip() removes the newline, giving "Ana 120", and split(" ") gives the list "Ana" and "120". The next calls give back the next lines. After the last line, readline() gives back an empty string, which means the end of the file. On Windows each line ends with \r\n on disk, but Python in text mode still gives back \n.
The first call reads up to the first newline. The read position now waits at the start of line 2.
3. Add a score with “a”
Save this as add_score.py. Append mode keeps the old lines and writes at the end.
name = input("Your name: ")
points = input("Your points: ")
with open("scores.txt", "a") as file:
file.write(name + " " + points + "\n")
print("Score added")
Run it with python3 add_score.py, and type Mateo and 130. You should see:
Your name: Mateo
Your points: 130
Score added
Now scores.txt contains:
Ana 120
Luis 95
Sofia 140
Mateo 130
Run read_scores.py again, and Mateo appears in the list. The data survived between two different programs. That is persistence.
4. Open a missing file
The first time a program runs, its files often do not exist yet. Save this as read_missing.py. It tries to read players.txt, which you never created.
with open("players.txt", "r") as file:
print(file.read())
Run it with python3 read_missing.py. Python stops with an error. The last line says:
FileNotFoundError: [Errno 2] No such file or directory: 'players.txt'
Read mode needs the file to exist. Check first with os.path.exists, which returns True when the file is there. Save this as read_safe.py:
import os
if os.path.exists("players.txt"):
with open("players.txt", "r") as file:
print(file.read())
else:
print("No players yet. Play a game first.")
Run it with python3 read_safe.py. You should see:
No players yet. Play a game first.
Design a file format
A text file has no rules about what goes inside. Your program decides the format: what each line means and how the values are separated. In the score board, the format is “one player per line, name and points separated by one space”.
Saving means turning your data into text. Loading means turning text back into data. Both are plain logic with strings and arrays, so they run in StepCode. This program joins four numbers into one line, ready to save, and then splits that line back into numbers.
When you type 2, 0, 16 and 4, you should see:
Line to save: [2 0 16 4]
Numbers read back: 4
copy[1] = 2, times 2 = 4
copy[2] = 0, times 2 = 0
copy[3] = 16, times 2 = 32
copy[4] = 4, times 2 = 8
ToNumber gives back a Real, and Trunc turns it into an Integer. It is the same job that int() does in Python. You will use this exact idea in the final project to save a game board.
Sort numbers from a file
This is Activity 5 from the course. A file called numbers.txt has one number on each line. The program reads the numbers, sorts them with bubble sort, and writes them line by line into sorted.txt.
5. Write the sorting logic
First, solve the part that has nothing to do with files. In StepCode, you type the numbers instead of reading them from a file. Each Read plays the role of one line of the file.
When you type 9 and then 5, 8, 6, 2, 4, 3, 2, 8 and 5, you should see:
How many numbers?
Sorted, one per line:
2
2
3
4
5
5
6
8
8
6. Sort a file in Python
Now replace the keyboard with files. Create numbers.txt with these lines:
5
8
6
2
4
3
2
8
5
Save this as sort_file.py. It has one function to read, one to sort and one to write, so each job is easy to check on its own.
def read_numbers(file_name: str) -> list[int]:
numbers = []
with open(file_name, "r") as file:
for line in file.readlines():
numbers.append(int(line))
return numbers
def bubble_sort(numbers: list[int]) -> None:
n = len(numbers)
for i in range(n - 1):
for j in range(n - 1 - i):
if numbers[j] > numbers[j + 1]:
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
def write_numbers(file_name: str, numbers: list[int]) -> None:
with open(file_name, "w") as file:
for number in numbers:
file.write(str(number) + "\n")
numbers = read_numbers("numbers.txt")
print("Read:", numbers)
bubble_sort(numbers)
write_numbers("sorted.txt", numbers)
print("Wrote:", numbers)
Run it with python3 sort_file.py. You should see:
Read: [5, 8, 6, 2, 4, 3, 2, 8, 5]
Wrote: [2, 2, 3, 4, 5, 5, 6, 8, 8]
And sorted.txt now has the numbers in order, one per line: 2, 2, 3, 4, 5, 5, 6, 8, 8. Compare bubble_sort with the BubbleSort procedure in StepCode. The logic is the same. Only the source of the numbers changed.
Common mistakes
If all your lines end up glued together, like AnaLuis, it means you forgot the newline. write writes exactly what you give it and adds nothing. Add "\n" at the end of each line.
If a file lost its old content, it means you opened it with "w" when you wanted "a". Write mode always empties the file first. Use "a" to add, and keep "w" for when you rewrite the whole file on purpose.
If you see FileNotFoundError, it means you opened a file in "r" mode that does not exist, or that is in another folder. Check the name, run the program from the folder that has the file, and use os.path.exists for files that may not exist yet.
If your numbers sort in a strange order, like 10 before 9, it means you are sorting text. Text compares letter by letter, in the dictionary order from Strings, and "1" comes before "9". In Python, "10" < "9" is True, while 10 < 9 is False. Convert every value with int() or float() right after you read it.
Files are not databases
A text file is perfect for small amounts of data that one program uses: settings, a score list, a saved game. It is not a good fit when many users change the same data at once, or when you need to search millions of records fast. That is the job of a database, a program built to store, search and protect data. Databases still save their data in files on a disk, but they manage those files for you.
Files are also different from variables. A variable is fast and disappears when the program ends. A file is slower and survives.
Practice exercises
Write each program in Python. Try it before you open the solution.
Exercise 1: count lines and words
Write a function that receives a file name and writes how many lines and words the file has. Words are separated by spaces.
Solution
def count_lines_and_words(file_name: str) -> None:
lines = 0
words = 0
with open(file_name, "r") as file:
for line in file.readlines():
lines = lines + 1
words = words + len(line.split())
print(file_name, "has", lines, "lines and", words, "words")
with open("notes.txt", "w") as file:
file.write("Files keep data\n")
file.write("after the program ends\n")
count_lines_and_words("notes.txt")You should see:
notes.txt has 2 lines and 7 wordsExercise 2: a winners list
The final project asks for this. Keep a file winners.txt with one winner per line and the number of times they won. When someone wins, add 1 to their count, or add a new line if it is their first win.
Solution
The program loads the file into two arrays (Python lists), changes them in memory, and rewrites the whole file with "w".
import os
def read_winners(file_name: str, names: list[str], wins: list[int]) -> None:
if os.path.exists(file_name):
with open(file_name, "r") as file:
for line in file.readlines():
name, count = line.strip().split(" ")
names.append(name)
wins.append(int(count))
def write_winners(file_name: str, names: list[str], wins: list[int]) -> None:
with open(file_name, "w") as file:
for i in range(len(names)):
file.write(names[i] + " " + str(wins[i]) + "\n")
names = []
wins = []
read_winners("winners.txt", names, wins)
name = input("Winner name: ")
if name in names:
position = names.index(name)
wins[position] = wins[position] + 1
else:
names.append(name)
wins.append(1)
write_winners("winners.txt", names, wins)
print("Wins for", name + ":", wins[names.index(name)])Run it three times, typing Rolando, Ana and Rolando. You should see:
Winner name: Rolando
Wins for Rolando: 1
Winner name: Ana
Wins for Ana: 1
Winner name: Rolando
Wins for Rolando: 2And winners.txt contains:
Rolando 2
Ana 1Exercise 3: the music box
The course files include a small music box program. You type notes like CDEC, the computer plays them, and you can save the song to music.txt. The original used winsound, which only works on Windows. Write a version that prints the notes instead, keeps every saved song with append mode, and can play all saved songs.
Solution
import os
def play(notes: str) -> None:
# The class version beeped with winsound (Windows only). Here we print.
for note in notes:
if note in "CDEFGAB":
print(note, end=" ")
else:
print("-", end=" ")
print()
def record_song() -> None:
notes = input("Type notes (C D E F G A B): ")
play(notes)
answer = input("Save it? [Y/n]: ")
if answer.lower() != "n":
with open("music.txt", "a") as file:
file.write(notes + "\n")
def play_saved_songs() -> None:
with open("music.txt", "r") as file:
for line in file.readlines():
play(line.strip())
def main() -> None:
print("What do you want to do?")
print(" [1] Record a song")
print(" [2] Play saved songs")
print(" [3] Delete the file")
answer = int(input("R: "))
if answer == 1:
record_song()
elif answer == 2:
play_saved_songs()
elif answer == 3:
os.remove("music.txt")
main()Run it and choose 1, type CDEC and answer y. You should see:
What do you want to do?
[1] Record a song
[2] Play saved songs
[3] Delete the file
R: 1
Type notes (C D E F G A B): CDEC
C D E C
Save it? [Y/n]: yRecord a second song, EFG, the same way. Then run it again and choose 2. You should see:
What do you want to do?
[1] Record a song
[2] Play saved songs
[3] Delete the file
R: 2
C D E C
E F GWhat you learned
- Variables live in memory and disappear when the program ends. Files live on a disk and keep data. This is persistence.
- Text files hold readable characters, and each line ends with a newline,
\n. open(name, mode)opens a file."r"reads,"w"erases and writes, and"a"adds to the end.withcloses the file for you.- Everything you read from a text file is text. Convert numbers with
int()orfloat(). - Your program decides the file format. Saving turns data into text, and loading turns text back into data.
Next steps
You now know every piece you need for a real program. In the last lesson, the final project, you plan and build a complete game with everything from this series.
- Review Procedures and functions, because the project is built from small subprograms.
- Read the Python tutorial on reading and writing files for more methods.