Part 8: The Captain's Log — Reading and Writing Files
The Adventures of Ava the Astronaut: Learning Python One Planet at a Time
Part 8: The Captain’s Log — Reading and Writing Files
The Adventures of Ava the Astronaut: Learning Python One Planet at a Time
A Fading Memory
Ava’s journey had been long and eventful. She had created an encyclopedia of aliens, a detailed inventory of her cargo, and a list of all the star systems she had visited. All this data was stored in variables, lists, and dictionaries. But she noticed a major problem.
Every time she had to restart her ship’s computer, all her data was lost! The variables would be wiped clean, and her inventory and encyclopedia would become empty again. All that precious information vanished as if it had never existed.
“Py, this is a disaster!” Ava exclaimed. “My mission logs, my discoveries… they all disappear when the power cycles. How can I save my work permanently?”
“An astute observation, Commander,” Py replied. “Everything you have stored so far lives in the computer’s RAM (Random Access Memory), which is volatile — it is cleared when the computer loses power. To save data permanently, you must write it to a file on the ship’s hard drive.”
The Ship’s Library: Working with Files
Think of your computer’s hard drive as a library, and files are the books on its shelves. You can create new books, write in them, read them later, and add more pages. Python gives us the tools to do all of this.
The most important function for working with files is open(). It takes two main arguments: the file name (or path) and the mode, which tells Python what you want to do with the file.
| Mode | Name | What It Does |
|---|---|---|
'r' | Read | Opens an existing file for reading. This is the default mode. Raises an error if the file does not exist. |
'w' | Write | Opens a file for writing. Warning: If the file already exists, its contents are completely erased! If it does not exist, a new one is created. |
'a' | Append | Opens a file for appending. New data is added to the end of the file without erasing anything. If the file does not exist, a new one is created. |
The with Statement: Safe File Handling
When you open a file, you must also remember to close it when you are done. Forgetting to close files can lead to data corruption or other problems. Fortunately, Python has a special, safer way to handle files using the with statement. It automatically closes the file for you when the indented block of code finishes, even if an error occurs.
Let’s help Ava write her first entry in the Captain’s Log.
# Use 'with' to open a file for writing ('w' mode)with open("captains_log.txt", "w") as log_file: log_file.write("Captain's Log: Stardate 47634.1\n") log_file.write("We have discovered that computer memory is volatile.\n") log_file.write("Beginning experiments with permanent file storage.\n")
print("First log entry saved successfully!")What happens?
This code creates a new file named captains_log.txt in the same folder as your Python script. It writes three lines of text into it. The \n at the end of each string is a special character that means “new line,” ensuring each entry starts on a fresh line.
The variable name log_file (after the as keyword) is the file object — it is our handle to interact with the open file. When the indented block under with finishes, the file is automatically and safely closed.
Adding More Entries: Append Mode
Now Ava wants to add a second entry to her log without erasing the first one. This is where append mode ('a') comes in.
# Open the same file in APPEND mode to add more textwith open("captains_log.txt", "a") as log_file: log_file.write("\nCaptain's Log: Stardate 47635.2\n") log_file.write("File storage experiment was a success!\n") log_file.write("All previous data has been preserved.\n")
print("Second log entry appended!")If we had used 'w' mode here instead of 'a', the first entry would have been erased and replaced with the new text. Always use 'a' when you want to add to an existing file.
Reading the Captain’s Log
What good is a log if you can’t read it? Let’s open the file in read mode ('r') and see what is inside.
# Open the file for readingwith open("captains_log.txt", "r") as log_file: log_content = log_file.read()
print("--- Reading Captain's Log ---")print(log_content)print("--- End of Log ---")The .read() method reads the entire content of the file and stores it as a single string in the log_content variable.
You can also read a file line by line, which is very useful for processing large files:
with open("captains_log.txt", "r") as log_file: line_number = 1 for line in log_file: print(f"Line {line_number}: {line.strip()}") # .strip() removes the \n line_number += 1A Quick Summary of File Operations
Here is a handy reference table for the file operations you have learned:
| Operation | Code | Description |
|---|---|---|
| Write (create/overwrite) | open("file.txt", "w") | Creates a new file or erases an existing one. |
| Append (add to end) | open("file.txt", "a") | Adds content to the end of a file. |
| Read entire file | file.read() | Returns all content as a single string. |
| Read line by line | for line in file: | Iterates through each line of the file. |
Mini-Project: “Mission Log System”
Your mission is to create a simple logging system for Ava. The program should let the user add new log entries and also read all past entries.
Your Task:
- Ask the user: “Would you like to (1) Add a log entry or (2) Read the log?”
- If the user chooses 1:
- Use
input()to ask, “What is your log entry for today?” - Open the file
mission_log.txtin append mode ('a'). - Write the user’s log entry to the file, followed by a
\n. - Print a confirmation message: “Log entry saved.”
- Use
- If the user chooses 2:
- Open the file
mission_log.txtin read mode ('r'). - Read and print all the contents of the file.
- If the file does not exist yet, print a message like “No logs found yet.”
- Open the file
Bonus Challenge: Add a timestamp to each log entry! You can use from datetime import datetime and then datetime.now() to get the current date and time.
Mission Complete!
You have secured Ava’s legacy! You now know how to save data permanently by writing to files, add to existing files with append mode, and read data back. This is a critical skill for any programmer, as it allows your applications to remember information between sessions — your data will survive even a spaceship reboot.
But what happens when things go wrong? In our next mission, we will put up our “Space Shields” and learn how to handle errors gracefully without crashing our program! See you in Part 9!
This is Part 8 of a 10-part series: “The Adventures of Ava the Astronaut: Learning Python One Planet at a Time.”