Data inside variables (like score = 10) is lost when the program ends.
But Files are forever. They live on your hard drive (or in the cloud) even after Hoppy goes to sleep.
Opening a Book
Reading a file is like reading a book:
- Open it.
- Read it.
- Close it.
# "r" means "read mode"
file = open("message.txt", "r")
text = file.read()
print(text)
file.close() # Always close it!
1
The Secret Diary
We have found a diary.txt file in the library. It contains a secret message. You don't need to create it, it's already there!
2
Open it
In main.py, use open("diary.txt", "r") and save it to a variable named file.
3
Read & Print
Call file.read() to get the text. Print it out to see your secret! Then file.close() it.
If you try to open a file that doesn't exist, Python will crash with FileNotFoundError!
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
# 1. Open
file = open("diary.txt", "r")
# 2. Read
secret = file.read()
print("Diary says: " + secret)
# 3. Close
file.close()Advanced TipsWant more? Click to expandClick to collapse
F. Context Managers (with)
- Professional Python coders rarely type
file.close(). - They use
with open(...) as file:. - This magic block automatically closes the file when you leave it, even if an error happens!
Loading...
Terminal
Terminal
Ready to run...