Home · Academy · Robotics & Coding · Python Fundamentals · Getting Started with Files

Getting Started with Files

Learn to read and write text files safely using with open.

LESSON COMPASS

What will you use this page for?

Core idea

We learn how to write text into a file and read it back, so our data is not lost even after the program closes.

Evidence to produce

Complete the page task with your own input, test conditions and reasoning.

Control trap

Forgetting the \n If you do not add a newline to every f.write(...) call, all the items join on one line: Buy milkReturn the book . Make it a habit to add \n at the end of each line. Erasing data by accident with "w" Opening an existing file in "w" mode erases the old content instantly. Use "a" if you want to add…

Next connection

Randomness and Simple Game Logic: With the random module we will learn to roll dice, make random choices, and build our first small guessing game.

Module sources: Python Tutorial · Arduino Learn

LevelBeginner
Age10–16
Duration30–45 min
PrerequisiteReading Error Messages
ContentStandard lesson · 1,665 words
Last updated

One-sentence summary

We learn how to write text into a file and read it back, so our data is not lost even after the program closes.

Why does this matter?

Until now, the programs you wrote forgot everything the moment they finished. You typed a number, something appeared on the screen, and the program closed. The next day, when you opened it again, it remembered nothing.

Real applications do not work like that. A game wants to keep its high score, an app wants to keep your settings, and a robot wants to keep the measurements it collected. It wants to save them. The simplest way to do this is to write the data into a file.

A file is a named box of information stored on the computer's disk. Even when the program closes, the file stays on the disk. In this lesson we will work with plain-text files that end in .txt, because they are the easiest kind of file to read and understand.

Short definition: A file is a named storage area that stays on the disk even after a program closes.

Writing to a file and reading from it

The with open(...) pattern

To work with a file, we first open it. In Python, the safe way to do this is the with open(...) as f pattern.

with open("notes.txt", "w") as f:
    f.write("Today I am learning Python\n")

Let us read these lines piece by piece:

The code under the with line is written with a 4-space indent so that it stays inside. The indent shows that those lines belong to the with block.

The \n at the end of the text is a newline character. It moves us to a new line, a bit like pressing "enter" on a page.

Reading the file back

To read the file we wrote, we change the mode to "r" (read).

with open("notes.txt", "r") as f:
    content = f.read()

print(content)

f.read() gives us the whole content of the file as one piece of text. We stored it in the content variable and printed it. In the terminal we see:

Today I am learning Python

Note: when reading, the file must already exist on the disk. If you try to open a missing file in "r" mode, you get a FileNotFoundError. If that sounds familiar, good; we practised reading error messages in the previous lesson.

Do not mix up the modes

There are three basic modes:

Do not mix up the modes table
ModeMeaningWhat it does
"r"readReads the file (cannot write)
"w"writeWrites from scratch, erases the old content
"a"appendAdds to the end, keeps the old content

Remember that "w" mode erases the old content. If you want to add a new line to an existing file, you must use "a" mode.

Working line by line

Writing several lines

Most of the time we want to save a list, not just one sentence. Let us write each item on its own line.

notes = ["Buy milk", "Return the book", "Finish homework"]

with open("notes.txt", "w") as f:
    for item in notes:
        f.write(item + "\n")

Here the for loop walks through each item in the list one by one. item + "\n" adds a newline to the end of each item, so the items are stacked on top of each other. The file now looks like this:

Buy milk
Return the book
Finish homework

Reading the lines one by one

We can also read a file line by line with a for loop. This does not strain memory even with very large files.

with open("notes.txt", "r") as f:
    for line in f:
        print("- " + line.strip())

The line.strip() here is a small but important detail. It removes the invisible \n character at the end of each line; otherwise you get extra blank lines between items on the screen. Output:

- Buy milk
- Return the book
- Finish homework

Adding a new item to the end

When you run the program again, "w" would erase everything. To keep the old notes and add a new one, we use "a" mode.

with open("notes.txt", "a") as f:
    f.write("Water the plants\n")

This code does not erase the file; it just adds one more line to the bottom. Now the file has four items.

Mini practice

We will write a small "notebook" program: it takes three notes from the user, writes them to a file, and then reads them back with numbers.

notes = []
for i in range(3):
    new_note = input(f"Write note {i + 1}: ")
    notes.append(new_note)

with open("notebook.txt", "w") as f:
    for item in notes:
        f.write(item + "\n")

print("\nContents of the notebook:")
with open("notebook.txt", "r") as f:
    number = 1
    for line in f:
        print(str(number) + ". " + line.strip())
        number = number + 1

Let us follow what happens:

  1. We created an empty notes list.
  2. The for i in range(3) loop asked the user for a note three times and added it to the list.
  3. We wrote the list to notebook.txt line by line.
  4. We opened the same file again and printed each line with a number.

Run the program. Then close it and, without running it again, open the notebook.txt file in your project folder with a text editor. Are the things you typed still there? If they are, you have successfully made your data permanent.

Common mistakes

Forgetting the \n

If you do not add a newline to every f.write(...) call, all the items join on one line: Buy milkReturn the book. Make it a habit to add \n at the end of each line.

Erasing data by accident with "w"

Opening an existing file in "w" mode erases the old content instantly. Use "a" if you want to add notes, and "r" if you only want to read.

Forgetting strip()

If you do not use strip() when reading lines, the trailing \n gives you extra blank lines in the output. Clean the lines when you print them.

Trying to read a file that does not exist

If you open a file you have not written yet in "r" mode, you get a FileNotFoundError. Write first, then read; or make sure the file really is in the folder.

Safety note

Follow a few simple rules when working with files:

Review questions

  1. Why should a program specify a text encoding when reading or writing files?
  2. What is the difference between write mode and append mode?
  3. How does a with block help file safety?
  4. What checks should happen before a program overwrites a file?
  5. Why must data loaded from a file still be validated?
  6. What test protects against losing an existing project record?

Answers

  1. An explicit encoding such as UTF-8 makes character interpretation more predictable across systems.
  2. Write mode replaces existing content, while append mode adds content to the end of an existing file.
  3. It closes the file reliably even if an error occurs inside the block.
  4. Confirm the path, create a backup or use a new output name, and ask for confirmation when data loss is possible.
  5. Files can be incomplete, edited, outdated or malicious; format and range checks are still required.
  6. Run the program on a temporary copy and verify that the original file remains unchanged.

Lesson summary

Check-your-understanding questions

  1. What does the "r" in the line with open("data.txt", "r") as f mean?
  2. If you open an existing file in "w" mode, what happens to its old content?
  3. If you write f.write("Hello") without adding a newline, what happens?
  4. Which mode do you use to add a new line to the end of a file without erasing the old content?
  5. When reading lines, what does line.strip() do?

Answers

  1. "r" is read mode. The file can only be read, not written to.
  2. The old content is completely erased. "w" writes the file from scratch, so it must be used carefully.
  3. The next text you write joins on the same line as the previous one. To stack lines, you need to add "\n".
  4. The "a" (append) mode. The old lines are kept, and the new line is added at the end.
  5. It removes the invisible \n (newline) character at the end of each line, so no extra blank lines appear in the output.

Source and verification note

For “Getting Started with Files”, verification focuses on whether the relationship between Why does this matter? and The with open(...) pattern remains consistent across examples. Code examples follow Python 3 syntax. Small differences may appear between environments, so examples should first be tested in a safe online editor or a local development setup.

End-of-lesson check

  1. How would you define Getting Started with Files in your own words?
  2. What is one normal use of the structure learned in this lesson?
  3. Which boundary or unexpected case would you test?
  4. How could you detect and correct one likely mistake?
  5. How would you adapt the same idea to another robotics or coding project?

End-of-lesson check — sample answers

  1. A good definition explains both the main idea and its purpose.
  2. The example should identify the input, the process and the resulting output.
  3. A boundary test can use the lowest or highest accepted value; an unexpected test can use missing or invalid input.
  4. Compare expected and actual results, change one thing at a time and repeat the test.
  5. Find the rule that remains the same, then adapt the steps to the new project’s input, tool and output.

Next lesson

Randomness and Simple Game Logic: With the random module we will learn to roll dice, make random choices, and build our first small guessing game.

Start QuizBack to Python Fundamentals
QUESTION POOL

Reinforce this lesson with 10 questions

This lesson has a pool of 20 questions. Each attempt selects 10 and reshuffles the choices.