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:
open("notes.txt", "w")opens a file namednotes.txt."w"is the mode."w"means write. If the file does not exist, it is created.as fgives the opened file the namef; from now on we refer to it asf.- When the
withblock ends, the file closes by itself. Python handles that for us so we do not forget.
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:
| Mode | Meaning | What it does |
|---|---|---|
"r" | read | Reads the file (cannot write) |
"w" | write | Writes from scratch, erases the old content |
"a" | append | Adds 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:
- We created an empty
noteslist. - The
for i in range(3)loop asked the user for a note three times and added it to the list. - We wrote the list to
notebook.txtline by line. - 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:
- Only open and run files you created yourself, or files your teacher or parent trusts. Do not blindly run unfamiliar code you downloaded from the internet.
- Do not write personal information into files: passwords, addresses, phone numbers, ID numbers, or family details should not be stored in code files.
- The
"w"mode can erase a file's content. Run a program that deletes or overwrites files in a separate practice folder, not in a folder with important files. - If you are unsure about a file operation, do it together with an adult.
Review questions
- Why should a program specify a text encoding when reading or writing files?
- What is the difference between write mode and append mode?
- How does a with block help file safety?
- What checks should happen before a program overwrites a file?
- Why must data loaded from a file still be validated?
- What test protects against losing an existing project record?
Answers
- An explicit encoding such as UTF-8 makes character interpretation more predictable across systems.
- Write mode replaces existing content, while append mode adds content to the end of an existing file.
- It closes the file reliably even if an error occurs inside the block.
- Confirm the path, create a backup or use a new output name, and ask for confirmation when data loss is possible.
- Files can be incomplete, edited, outdated or malicious; format and range checks are still required.
- Run the program on a temporary copy and verify that the original file remains unchanged.
Lesson summary
- A file is a storage area that stays on the disk even after the program closes.
- The
with open(...) as fpattern opens a file safely and closes it by itself when the work is done. "r"reads,"w"writes from scratch and erases the old content, and"a"adds to the end.- With
for line in fwe can read a file line by line;strip()removes the trailing\ncharacter. - Work only with files you trust, and do not write personal information into files.
Check-your-understanding questions
- What does the
"r"in the linewith open("data.txt", "r") as fmean? - If you open an existing file in
"w"mode, what happens to its old content? - If you write
f.write("Hello")without adding a newline, what happens? - Which mode do you use to add a new line to the end of a file without erasing the old content?
- When reading lines, what does
line.strip()do?
Answers
"r"is read mode. The file can only be read, not written to.- The old content is completely erased.
"w"writes the file from scratch, so it must be used carefully. - The next text you write joins on the same line as the previous one. To stack lines, you need to add
"\n". - The
"a"(append) mode. The old lines are kept, and the new line is added at the end. - 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
- How would you define Getting Started with Files in your own words?
- What is one normal use of the structure learned in this lesson?
- Which boundary or unexpected case would you test?
- How could you detect and correct one likely mistake?
- How would you adapt the same idea to another robotics or coding project?
End-of-lesson check — sample answers
- A good definition explains both the main idea and its purpose.
- The example should identify the input, the process and the resulting output.
- A boundary test can use the lowest or highest accepted value; an unexpected test can use missing or invalid input.
- Compare expected and actual results, change one thing at a time and repeat the test.
- 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.