Working with Files
Save your program's data and read it back later
- open a text file with
open(), - write text to a file and read it back,
- use the safe
with open(...)pattern that closes the file for you.
1. What is a file?
A file is a place on your computer's disk where information is stored with a name, like notes.txt. Unlike a variable, a file stays there even after your program ends or your computer turns off.
Analogy: A variable is like something you hold in your hand — the moment you let go (the program ends), it is gone. A file is like a notebook: you write in it, close it, put it on a shelf, and open it again tomorrow to read what you wrote.
In this topic we work with text files (files full of ordinary characters, like .txt).
2. Open, use, close
To use a file you always do three things in order:
You open a file with the built-in open() function. You give it the file name and a mode that says what you want to do:
| Mode | Meaning |
|---|---|
"r" | Read an existing file (this is the default). |
"w" | Write — creates the file, or erases it if it already exists. |
"a" | Append — adds to the end, keeping what is already there. |
When you finish, you must close the file with .close(). Closing saves your changes and frees the file for other programs:
f = open("notes.txt", "w")
f.write("Hello, file!")
f.close()
This works, but it is easy to forget close() — especially if an error happens before you reach it. There is a safer way, coming next.