Until now your programs lost everything when they ended: variables only live while the program runs. Files let you store data permanently and read data that already exists.
open() and the modes
open(name, mode) opens a file and returns an object to read from or write to. The mode says what you are going to do:
| Mode | What it does | If the file does not exist | If it already exists |
|---|---|---|---|
"r" | Read (default) | FileNotFoundError | reads it |
"w" | Write | creates it | deletes all its content |
"a" | Append at the end | creates it | keeps what is there and adds after it |
with: opening and closing safely
An open file must be closed, or the data may not get saved. with does it by itself, even if an error occurs inside the block:
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("Hello\n")
# here the file is already closed
file is the name we give to the object, and the indented block is where it can be used.
The encoding
A text file stores numbers; the encoding defines which number corresponds to each letter. The most widely used today is UTF-8, which supports accents, special letters, symbols and emojis. Always write encoding="utf-8" to avoid surprises, especially if the program runs on different systems.
The path of the file
"notes.txt": relative path, the file is in the folder the program is run from."data/notes.txt": inside thedatasubfolder (the folder must exist)."C:/Users/ana/notes.txt": absolute path. Use/on Windows too, or write\\, because a single\is a special character.
Checking whether it exists
import os
if os.path.exists("notes.txt"):
print("It exists")
else:
print("It does not exist")
If the file does not exist when reading
with open("missing.txt", "r", encoding="utf-8") as f:
print(f.read())
# FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
You can handle it with try/except FileNotFoundError to show a message instead of the program crashing.