---
title: "Reading and Writing Text Files for Beginners: Programming Fundamentals (13)"
date: "2026-11-08"
description: "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."
tags: ["Programming Fundamentals", "Tutorials"]
url: "https://rolandoandrade.me/blog/programming-fundamentals-files/"
author: "Rolando Andrade"
---

# 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.

*Figure: Step through two runs of a score program. Memory is cleared when the program ends. The file on the disk is still there for the next run.*

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](/blog/programming-fundamentals-strings/#characters-inside-a-computer).
- **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:

```text
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. |

*Figure: Pick a mode, and choose if the file already exists. "w" erases the old lines before it writes, "a" adds to the end, and "r" and "x" fail in opposite cases.*

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.

```python
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:

```text
Saved 3 scores
```

Open `scores.txt` in a text editor. It contains:

```text
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.

```python
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:

```text
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](/blog/programming-fundamentals-programming-languages/#5-run-the-same-idea-in-python-and-find-the-hidden-bug).

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.

*Figure: Press readline() a few times. Each call stops after a newline, strip() removes it, and an empty string means the file ended.*

### 3. Add a score with "a"

Save this as `add_score.py`. Append mode keeps the old lines and writes at the end.

```python
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:

```text
Your name: Mateo
Your points: 130
Score added
```

Now `scores.txt` contains:

```text
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.

```python
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:

```text
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`:

```python
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:

```text
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.

**Turn numbers into a line of text and back** (StepCode)

```stepcode
Program SaveFormat
    Define row, copy As Integer;
    Dimension row[4], copy[4];
    Define line As String;
    Define i, count As Integer;
    For i <- 1 To 4 Step 1 Do
        Read row[i];
    EndFor
    // Before saving: turn the numbers into one line of text
    line <- JoinLine(row, 4);
    Write "Line to save: [", line, "]";
    // After loading: turn the line of text back into numbers
    count <- SplitLine(line, copy);
    Write "Numbers read back: ", count;
    For i <- 1 To count Step 1 Do
        Write "copy[", i, "] = ", copy[i], ", times 2 = ", copy[i] * 2;
    EndFor
EndProgram

// Joins the numbers with one space between them
Function JoinLine(list As Integer[], count As Integer): String
    Define result As String;
    Define i As Integer;
    result <- ToText(list[1]);
    For i <- 2 To count Step 1 Do
        result <- Concat(result, " " + ToText(list[i]));
    EndFor
    Return result;
EndFunction

// Splits a line at each space and stores the numbers. Returns how many it found.
Function SplitLine(line As String, list As Integer[]): Integer
    Define piece As String;
    Define i, count As Integer;
    piece <- "";
    count <- 0;
    For i <- 1 To Length(line) Step 1 Do
        If line[i] = " " Then
            count <- count + 1;
            list[count] <- Trunc(ToNumber(piece));
            piece <- "";
        Else
            piece <- piece + line[i];
        EndIf
    EndFor
    count <- count + 1;
    list[count] <- Trunc(ToNumber(piece));
    Return count;
EndFunction
```

When you type `2`, `0`, `16` and `4`, you should see:

```text
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](/blog/programming-fundamentals-final-project/#5-save-the-game-in-python) 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](/blog/programming-fundamentals-arrays/#sort-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.

**Bubble sort, the logic of Activity 5** (StepCode)

```stepcode
Program SortNumbers
    Define numbers As Integer;
    Dimension numbers[20];
    Define count, i As Integer;
    Write "How many numbers? ";
    Read count;
    // Each Read takes one number, like one line of numbers.txt
    For i <- 1 To count Step 1 Do
        Read numbers[i];
    EndFor
    BubbleSort(numbers, count);
    Write "Sorted, one per line:";
    For i <- 1 To count Step 1 Do
        Write numbers[i];
    EndFor
EndProgram

// Sorts the array from smallest to biggest
Procedure BubbleSort(list As Integer[], count As Integer)
    Define i, j, temp As Integer;
    For i <- 1 To count - 1 Step 1 Do
        For j <- 1 To count - i Step 1 Do
            If list[j] > list[j + 1] Then
                temp <- list[j];
                list[j] <- list[j + 1];
                list[j + 1] <- temp;
            EndIf
        EndFor
    EndFor
EndProcedure
```

When you type `9` and then `5`, `8`, `6`, `2`, `4`, `3`, `2`, `8` and `5`, you should see:

```text
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:

```text
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.

```python
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:

```text
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](/blog/programming-fundamentals-strings/#the-tools-for-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.

<details>
<summary>Solution</summary>

```python
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:

```text
notes.txt has 2 lines and 7 words
```

</details>

### Exercise 2: a winners list

The [final project](/blog/programming-fundamentals-final-project/#exercise-3-the-full-brief) 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.

<details>
<summary>Solution</summary>

The program loads the file into two arrays (Python lists), changes them in memory, and rewrites the whole file with `"w"`.

```python
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:

```text
Winner name: Rolando
Wins for Rolando: 1
Winner name: Ana
Wins for Ana: 1
Winner name: Rolando
Wins for Rolando: 2
```

And `winners.txt` contains:

```text
Rolando 2
Ana 1
```

</details>

### Exercise 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.

<details>
<summary>Solution</summary>

```python
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:

```text
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]: y
```

Record a second song, `EFG`, the same way. Then run it again and choose `2`. You should see:

```text
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 G
```

</details>

## What 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. `with` closes the file for you.
- Everything you read from a text file is text. Convert numbers with `int()` or `float()`.
- 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](/blog/programming-fundamentals-final-project/), you plan and build a complete game with everything from this series.

- Review [Procedures and functions](/blog/programming-fundamentals-procedures-and-functions/), because the project is built from small subprograms.
- Read the Python [tutorial on reading and writing files](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) for more methods.
