Welcome back, Gunters! In the OASIS, your programs need to be smart—they must read mission logs to uncover clues and write new data to track your progress, all without letting IOI crash your terminal. So far, you’ve learned to read files (like scanning Halliday’s archives) and write files (like logging artifact discoveries). Today, we’re combining these skills to make your programs even more powerful!
In this lesson, you’ll learn how to parse structured data (like leaderboard rankings), handle tricky errors, manage files by deleting or renaming them, and monitor file sizes to keep your OASIS terminal running smoothly. These skills are like upgrading your avatar with new gear—essential for tackling real-world challenges and preparing for your final mission: a full OASIS command terminal project!
🔍 Parse and format structured data by reading files, extracting information, and writing organized output.
🛡️ Use advanced error handling to catch specific errors and validate user input for robust programs.
🗑️ Manage files by safely deleting or renaming them to reset or archive OASIS data.
📏 Monitor file size to ensure logs don’t grow too large, simulating real-world constraints.
🔄 Combine reading and writing to create programs that process and update files in one go.
🎮 Apply these skills in OASIS-themed tasks to prepare for your final project.
✂️ Understand and use split() to break strings into manageable pieces for parsing data.
We're going to stay in the theme of Ready Player One, and visit the OASIS!! Get Ready!
Imagine you’re Parzival, updating a leaderboard after finding the Copper Key. You need to read the current rankings, check for your name, and write your new score—all without erasing everyone else’s data! Combining reading and writing lets your programs:
Load and modify saved data (like game scores or mission logs).
Create reports or summaries from raw files.
Handle files safely, even when things go wrong (like IOI hacking your terminal).
Game Development: Read a player’s saved progress, update their score, and write it back.
Data Analysis: Read a CSV file, extract specific records, and write a summary report.
Logging Systems: Read a log to check past events, then append new actions with timestamps.
Before we can get into file parsing and formatting, we need to look at a new function called split( )
The split() function is like a laser cutter for string
It chops a string into a list of smaller strings based on a separator (like a comma, space, or colon).
For Example:
“1,parzival,wade watts”
split(",") breaks it into
["1", "parzival", "wade watts"]
This is super useful for reading files with structured data, like splitting a log entry into username and event.
Split will separate everything into a list based on the character :
In the OASIS, files like leaderboard.txt store data in a structured format (e.g., “rank,username,real_name”).
Parsing means reading that file and breaking it into pieces (like splitting a line into rank and username).
Formatting means writing data back in a clean, organized way (like a table or key-value pairs).
This is crucial for turning raw data into useful information, like displaying a leaderboard or summarizing mission logs.
STEP 1: You'll need to create the following TEXT file: mission_log.txt
parzival:Found Copper Key
art3mis:Defeated IOI Guard
parzival:Completed Jade Key Race
aech:Secured Orb of Osuvox
parzival:Entered Castle Anorak
aech:Fought at Distracted Globe
Read in this file
Using readlines( ), and split( ), see if you can print out the username and mission in a nice way
Bonus points if you can have your program create that file so you don't have to
BONUS TASK:
See if you can sort these by person!!
In the OASIS, you’re a Gunter managing secret mission logs. Sometimes, you need to delete a log to hide your tracks from IOI or rename it to save it as a backup. File deletion erases a file forever, like wiping a compromised data crystal. File renaming changes a file’s name, like relabeling a scroll for archiving. Python’s os module gives you two tools—os.remove() and os.rename()—to do this, but you must check if the file exists first to avoid glitches!
Both os.remove() and os.rename() can fail if the file doesn’t exist or is protected.
Using os.path.exists(filename) first checks if the file is there, like scanning the OASIS for a file before touching it.
This prevents errors and keeps your program crash-proof
Your projects might involve clearing old logs or saving backups, like archiving a mission report before IOI finds it.
These skills mimic real-world file management.
What It Does: Deletes the file named filename from your computer, like vaporizing a file in the OASIS.
Once it’s gone, it’s gone for good (no recycle bin in Python!).
How It Works:
You pass the name of the file (e.g., "player_log.txt") to os.remove(), and Python tells the operating system to delete it.
You need the os module, so import it first with import os.
When to Use It:
Use os.remove() when you want to permanently delete a file, like erasing an old log to keep IOI from finding it.
Potential Errors:
FileNotFoundError: If the file doesn’t exist, Python raises this error.
PermissionError: If the file is locked (e.g., open in another program), you can’t delete it.
IsADirectoryError: If you accidentally try to delete a folder instead of a file.
What It Does:
Changes the name of a file from old_name to new_name, like renaming a mission log from “player_log.txt” to “backup_log.txt”.
The file’s contents stay the same; only the name changes.
How It Works:
You pass two strings to os.rename(): the current filename and the new filename.
Python updates the file’s name in the operating system. You need import os for this too.
When to Use It:
Use os.rename() to archive files or organize data, like saving a log with a new name to mark it as a backup.
Potential Errors:
FileNotFoundError:
If the original file (old_name) doesn’t exist.
PermissionError:
If the file is locked or you don’t have permission to rename it.
FileExistsError:
If a file with new_name already exists (Python won’t overwrite it automatically).
Welcome, Gunter! You’re deep in the OASIS, managing secret mission logs to track your hunt for Halliday’s Easter egg. IOI is closing in, so you need a terminal to create, view, rename, or delete logs to stay one step ahead of Sorrento. Your program will use Python’s os module to handle files like a pro, just like Parzival hiding data from the Sixers. Ready to code your way to victory? This should take 20–25 minutes—let’s dive into the OASIS!
Start-Up Function:
Write a function create_initial_log() that checks if mission_log.txt exists using os.path.exists().
If it doesn’t, create it with 3 sample entries (e.g., “parzival:Found Copper Key”).
Menu Options:
1: View Mission Log:
Read and display mission_log.txt’s contents, parsing each line with split(":") to show username and mission.
BONUS:
Allow the user to select the delimiter that separates all the data
2: Rename Mission Log:
Rename mission_log.txt to “backup_mission_log.txt” using os.rename(), then read the renamed file to verify.
User must be prompted to rename and allowed to give a new name
3: Delete Mission Log:
Delete mission_log.txt using os.remove() after confirming with “Are you sure? (y/n)”.
BONUS: Prompt the user for the name of the file to delete
ERROR CHECK in case it doesn't exist!!!
4: Exit Terminal:
Exit with a message like “Disconnecting from OASIS...”.
Error Handling:
Catch FileNotFoundError, PermissionError, and FileExistsError with user-friendly messages.
Interactivity:
Use a while loop for the menu, validate user input, and provide OASIS-themed prompts.
File Format:
mission_log.txt should have entries like “username:mission” (e.g., “art3mis:Defeated IOI Guard”).
Bonus Activities (for early finishers):
Secret Log Entry:
Add a menu option “5: Add Secret Log” that prompts for a username and mission, then appends it to the current log with a timestamp
e.g., “2025-04-17 10:15:23 | parzival:Found Jade Key”
Use with open(filename, "a", encoding="utf-8")
datetime.now().strftime("%Y-%m-%d %H:%M:%S").
Action Tracker:
Create an action_log.txt file that records every rename or delete action with a timestamp (e.g., “2025-04-17 10:15:23: Renamed mission_log.txt to backup_mission_log.txt”).
Append each action using with and "a" mode