🐸

The Diary

Python Basicspython-architect-22-the-diary
Reward: 100 XP
|

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:

  1. Open it.
  2. Read it.
  3. 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 Solution
Expand
Solution:
# 1. Open
file = open("diary.txt", "r")

# 2. Read
secret = file.read()
print("Diary says: " + secret)

# 3. Close
file.close()
Advanced Tips
Want more? Click to expand

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...