We can read history, but we can also write it.
Hoppy wants to record the journey. We need to create a new file and save text into it.
The Writer's Quill
To write, we use the "w" mode (Write).
# "w" means "write mode"
file = open("story.txt", "w")
file.write("Once upon a time...")
file.close()
# Now "story.txt" contains that text!
1
Open for Writing
Use open("captain_log.txt", "w") and save it to file.
2
Write the Log
Call file.write(log_message). This sends the text from Python into the file.
3
Save & Close
Call file.close(). This is crucial! If you don't close, the file might remain empty or corrupted.
DANGER: "w" mode acts like a "New Game". It completely wipes out everything in the file before writing new text. Be careful!
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
# 1. Open for Writing
file = open("captain_log.txt", "w")
# 2. Write
file.write(log_message)
# 3. Save & Close
file.close()Advanced TipsWant more? Click to expandClick to collapse
F. Write Mode vs Read Mode
"r"= Read (Default). Safe."w"= Write. Destructive. Creates new file or overwrites existing."x"= Exclusive Creation. Fails if file already exists (Safe creation).
Loading...
Terminal
Terminal
Ready to run...