blog.dopana

Back

Welcome back, secret agent! 🕵️‍♂️

Up until now, whenever we closed our Python compiler, the robot completely forgot everything. That’s because the robot was only storing information in its temporary short-term memory (RAM).

Today, we are going to teach our robot how to write secret messages into files on your computer’s hard drive. They will stay there forever, even if you turn off your computer!

The Three Steps of File Magic (Open, Action, Close)#

Interacting with a file is just like writing a secret letter:

  1. Open: Open the drawer (or the envelope).
  2. Action: Write your message, or read what’s already written.
  3. Close: Close the drawer and seal the envelope. If you forget this step, your letter might get lost or ruined!
graph TD
    Start([Start]) --> Open["1. Open Envelope (open())"]
    Open --> Action["2. Write or Read (write() / read())"]
    Action --> Close["3. Seal Envelope (close())"]
    Close --> End([Done! Saved on Hard Drive 💾])

Writing a Secret Message ("w" mode)#

To write into a file, we tell Python to open() a file name in "w" (write) mode.

# 1. Open the file in "w" (write) mode
file = open("secret.txt", "w")

# 2. Write our secret message
file.write("The secret passcode is: Unicorn123 🦄")

# 3. Close the file to seal it
file.close()
python

When you run this code, Python will create a new file named secret.txt on your computer and save the text inside it!

[!WARNING] The "w" mode is aggressive. If the file secret.txt already exists, "w" will completely erase the old content and start fresh.

Reading the Secret Message ("r" mode)#

To read what is inside a file, we open it in "r" (read) mode:

# 1. Open the file in "r" (read) mode
file = open("secret.txt", "r")

# 2. Read the text inside
content = file.read()
print("Found a secret note:")
print(content)

# 3. Close the file
file.close()
python

Appending Messages ("a" mode)#

If you want to add text to the end of a file without erasing what’s already there, use "a" (append) mode instead of "w":

file = open("diary.txt", "a")
file.write("Today I learned file handling! 💻\n")
file.close()
python

(The \n symbol tells the robot to start a new line, like pressing the Enter key on your keyboard!)

Try It Yourself! 🎮#

Open your Python editor and try creating a diary logger:

  1. Ask the player: "What did you do today? " using input().
  2. Open a file named diary.txt in "a" mode.
  3. Write the player’s response followed by \n.
  4. Close the file.
  5. Open diary.txt in "r" mode, read the entire diary, and print it to the screen!

You have just unlocked the power of Persistence! Now you can save game high scores, player levels, and custom settings so players never lose their progress. Have fun writing your secrets! 🔒💾

References#