Working with Files
A file keeps its data after your program ends. The open function opens a file. When you open it in a with block, Python closes the file for you at the end of the block, even if an error happens inside it.
with open("notes.txt", "w") as f:
f.write("pack bags\n")
f.write("water plants\n")
with open("notes.txt") as f:
for line in f:
print(line.strip().upper())
Output:
PACK BAGS
WATER PLANTS
The "w" is the mode, and it means write. It creates the file, or empties it if it already exists. write adds text exactly as you give it, so you must end each line with \n yourself.
When you open a file without a mode, Python opens it for reading. A for loop then goes through the file one line at a time. Each line still has its \n at the end. That is why the code calls strip() before printing.
| Mode | File behavior |
|---|---|
"r" | Read a file that exists. This is the default |
"w" | Write a new file or replace its contents |
"a" | Add to the end of a file |
"x" | Create a new file, and fail if it already exists |
On your own computer, also pass encoding="utf-8" to open. Then the file is read the same way on every system. If you open a file for reading and it does not exist, Python raises FileNotFoundError.
In the exercise, write a shopping list to a file, then read it back with numbers.