Files let your programs remember things.
Direct answer
In Python, use open() inside a with block to read or write files. Use mode "r" to read, "w" to write and overwrite, and "a" to append. The with block closes the file automatically.
Read a file
with open("notes.txt", "r") as f:
text = f.read()
print(text)
Read line by line:
with open("notes.txt") as f:
for line in f:
print(line.strip())
Write a file
with open("out.txt", "w") as f:
f.write("Hello\n")
Use "a" to add to the end instead of overwriting.
File modes
| Mode | Meaning |
|---|---|
r | read (default) |
w | write, overwrites |
a | append |
r+ | read and write |
Handle missing files
try:
with open("data.txt") as f:
print(f.read())
except FileNotFoundError:
print("File not found")
Where Teyro fits
Teyro's Python for Beginners course turns this into short lessons you can play in a few minutes a day. It has 120 lessons, and you can start free.
The bottom line
Use with open(...), choose the right mode and handle the case where the file is missing.



