Programs that only read data without being able to save anything are like dry-erase boards—you can see the info while it’s running, but it disappears the moment you shut it down. Learning how to write to files gives your programs lasting memory: they can store high scores, log user input, create reports, generate documents, and even build entirely new files from scratch.
Whether you're saving game progress, logging sensor data, or exporting a list of usernames, file writing lets your programs leave a mark. It’s a critical step toward building interactive tools, dynamic apps, and systems that grow smarter over time. If file reading is how programs learn, then file writing is how they remember.
🔓 Open and write to text files using classic and modern Python methods
✍️ Use file writing methods like .write() and .writelines() to save content to a file
💾 Apply file modes like 'w' (write), 'a' (append), and 'x' (create only if it doesn't exist)
📍 Learn how writing moves the file pointer, and how to control it using .seek() and .tell()
✅ Understand when and why to use the with statement for writing files safely and cleanly
🔁 Practice saving data between runs, setting you up for real-world programs like logs, save files, or auto-generated content
To have a little fun with this topic, we're going to stay in the theme of Ready Player One, and visit the OASIS!! Get Ready!
As a quick Review, when we open files, we have modes which we use to tell it what we're going to be doing. Here are the popular ones you'll be working with... There are more (as you saw from the last chapter, but again, we'll focus on these for now!!
write() adds a single string to a file at the current file pointer position. If you want the text to appear on a new line, you need to manually include \n at the end of the string.
USAGE (BASIC):
Here's a typical way we'd use the OPEN method with our file mode, in order to write to a file. In this case, we're just overwriting, or creating a new file!!
.write() only writes exactly what you tell it to — no automatic line breaks.
writelines() writes a sequence of strings to a file all at once, exactly as they’re given. It doesn’t add newlines automatically, so you must include \n at the end of each line if you want line breaks in the file.
USAGE (BASIC):
Here's a typical way we'd use the OPEN method with our file mode, in order to write to a file. In this case, we're just overwriting, or creating a new file!!
.write() only writes exactly what you tell it to — no automatic line breaks.
There are a few examples included here that show:
writelines() with a list
writelines() with "multiline string"
BIG NOTE...
Look at the multiline string example. They are NOT COMMA SEPARATED!!! Python automatically joins adjacent strings when they're inside parentheses — no commas needed! We only need commas if it's a tuple, list, etc...
You're a Gunter inside the OASIS. Your team needs a command terminal that can log usernames, events, and artifact discoveries. You'll build a program that writes these logs to files using Python’s open(), .write(), and .writelines() methods. You'll also add error protection in case something goes wrong (looking at you, IOI).
Create a menu-driven terminal program with these options
Prompt users for information and create files with write and writelines
Before ANY File is created you must do a FILE CREATION CHECK
Before writing the log, check if the file already exists. If it does, warn the user and let them choose to:
Overwrite
Append
Cancel
To do this, we can use:
import os
file_exists = os.path.exists(filename)
Ask the user for:
OASIS Username (e.g., Parzival)
Event Description (e.g., “Completed the Copper Key race”)
Then:
Use .write() to save this to player_log.txt in this format:
Use 'a' mode so logs stack instead of overwrite.
This MUST be provided as a choice by a menu
Wrap it in try/except in case something breaks.
Prompt the user to enter information about 3 artifacts and ask what each one does. Store this information in a list
Then:
Use .writelines() to save all 3 lines at once to artifact_report.txt.
Use try/except here too in case anything breaks
Create a userlog entry any time someone writes to a file
It must include what they did, as well as a timestamp
I've given you the lines of code you need for that
This log can only be VIEWED by a SECRET ADMIN MODE which users can access if they enter a specific phrase (up to you what that is)
They need a way to exit this mode too...
To Get a Timestamp:
from datetime import datetime datetime.now().strftime("%Y-%m-%d %H:%M:%S")The with statement is like opening a secure vault in the OASIS — once you're done, it automatically closes the file for you, even if something goes wrong.
In earlier examples, you had to do this manually:
file = open("log.txt", "w")
file.write("Some data")
file.close() # Required
With with, you don't need file.close() — Python handles it automatically.
Syntax of with:
Here's how with looks (generic usage)
Real Usage of With
The 'a' mode means append — you're adding to the file without erasing the past.
Once the indented block is done, Python closes the file for you automatically.
Remember, from earlier, we can think of the file pointer like a cursor inside a scroll in the OASIS — it shows where Python is currently writing or reading.When you open a file for writing, the pointer starts at the beginning (unless you're appending). As you write, it moves forward.
Shows the current position of the pointer (in bytes from the start of the file)
Helpful for debugging or tracking how much you've written
Moves the file pointer to a specific byte
Can be used to overwrite text if you want to go back to the beginning or a specific point
Here's What it looks like if we ran that code!
When you write to a file (e.g., using file.write()), Python often holds the data in a temporary “buffer” (like a holding area) before actually saving it to the file. This saves time by reducing how often the computer talks to the disk.
But sometimes, you want the data saved immediately—that’s where flush() comes in. It tells Python, “Don’t wait! Save this to the file now!”
Real World Analogy: Imagine you’re writing notes in a notebook but only saving them when the page is full. flush() is like saying, “Save this note to the notebook right now, even if the page isn’t full!”
When you open a file in Python (e.g., with open("log.txt", "w") as file:), Python creates a file object. This object has properties that describe the file, like:
Its name.
The mode it’s opened in (e.g., write, append).
Whether it’s still open or closed.
Whether it’s readable or writable.
These properties are useful for:
Checking how a file is being used (e.g., to avoid mistakes like writing to a read-only file).
Debugging (e.g., making sure you’re working with the right file).
Building programs that need to verify file status, like an OASIS terminal logging user actions.
name:
What it tells you: The name of the file (e.g., "player_log.txt").
Why it’s useful: Confirms you’re working with the right file, especially if your program uses multiple files.
mode:
What it tells you: The mode the file was opened in (e.g., "w" for write, "a" for append, "r" for read).
Why it’s useful: Helps you check if the file is set up for writing, appending, or reading, so you don’t try the wrong operation.
closed:
What it tells you: Whether the file is still open (False) or has been closed (True).
Why it’s useful: Ensures the file is ready to use or confirms it’s safely closed to avoid errors.
readable():
What it tells you: Returns True if the file can be read, False otherwise.
Why it’s useful: Checks if you’re allowed to read the file (e.g., not if it’s opened in write-only mode).
writable():
What it tells you: Returns True if the file can be written to, False otherwise.
Why it’s useful: Ensures you can write or append to the file before trying.
You’re inside the OASIS Resistance base, running diagnostics on your mission logs. Parzival just uploaded a file containing coordinates and event data from a Halliday challenge. Your job is to inspect the file properties, log new data, verify write permissions, and ensure the file has been properly closed to avoid glitches.
Create a Python program that simulates an OASIS Terminal Menu with the following capabilities:
Write a new log entry
Display all key file properties (before and after writing)
Check if the file is ready for writing or reading
Show when the file is closed
Option 1: Write a mission log
Prompt for username and mission update (e.g., “Recovered the Zemeckis Cube”).
Use os.path.exists() to check if player_log.txt exists.
Let the user choose:
(o)verwrite – open in 'w' mode
(a)ppend – open in 'a' mode
(c)ancel – abort
Open the file using with, then:
Print the file’s name, mode, closed, and writable()
Write the entry (include timestamp)
Show closed status after the file block
Use file.flush() for good practice.
Option 2: View file properties
Open player_log.txt in read mode.
Display:
File name
Mode
Whether the file is closed
If it’s readable
If it’s writable
Confirm if file exists; create if not.
Option 3: Exit
Exit the loop with a message like:
Add a “Debug Report” that runs automatically after any write.
It checks: file.closed before and after writing
Whether the file is writable before the write attempt
What mode the file was in
Now You're going to write information to a file!
Try this, but make sure once done to look inside your file and see if it was created/written!
Remember... write will CREATE a file if it doesn't Exist!!!
Now You're going to write information to a file, but not overwrite it! We're going to append information!
Create a text file containing:
Name that file t_rex_data.txt
This will now read a line, tell you where the file pointer is, and then move the file pointer back to the beginning!
This is how you get good at reading a file non-sequentially!!
Use the t_rex_data.txt file from above
This will show you properties of the file!