In this lesson, you'll learn how to read text files using Python. Reading from files allows your programs to access stored information like saved game data, user inputs, logs, and more. Instead of asking users to retype information every time your program runs, you can load data directly from files. You'll explore different ways to open and read a file—from reading the entire file at once to processing it line by line. You'll also learn about two common approaches: the classic open() method and the modern pathlib module, which makes working with files more efficient and readable. These skills are essential for building real-world Python programs that need to store and retrieve information.
Open and read from text files using classic and modern Python methods
Use file reading methods like .read(), .readline(), and .readlines()
Apply file modes for reading
Understand when and why to use with for file handling
Begin practicing file-based operations for future projects
Programs that only work while they’re running—and forget everything afterward—are extremely limited. Being able to read from files gives your programs memory: they can load saved data, review past user input, display stored information, or even process massive datasets. Learning how to read files helps you build smarter, more useful programs that interact with the real world.
Whether you're pulling text from a game save file, importing a list of customer orders, or analyzing a huge dataset, file reading is an essential skill for every serious programmer. It’s one of the first steps toward working with real-world data.
When you’re working with files in Python using VS Code, you need to tell Python where your file is located on your computer. This “where” is called a file path.
Think of a file path like an address for your file—it’s how Python finds myfile.txt or data.txt on your computer. Without a file path, Python wouldn’t know which file to open, just like you wouldn’t know where to send a letter without an address!
In VS Code, you’ll often have a project folder open, and your files will be inside that folder or elsewhere on your computer. File paths help you point Python to the right spot, whether the file is in your project folder or somewhere else, like your Desktop.
An absolute file path is like giving Python the complete address of your file, starting from the very top of your computer’s file system. It includes every folder from the root (like C: on Windows or / on Mac/Linux) all the way to your file.
Path Separators:
Use / in paths (e.g., folder/file.txt), even on Windows
Avoid using \ unless you escape it (e.g., folder\\file.txt).
We use absolute paths when we need to be super specific, like if the file is in a completely different location from your VS Code project.
For example, if your file is on your Desktop, the absolute path makes sure Python can find it no matter where your Python script is running from.
A relative file path is a shorter way to tell Python where a file is, based on where your Python script is running in VS Code.
It’s like giving directions from your current location instead of starting from your city’s main street.
Relative paths are handy when your file is in the same folder as your script or in a nearby folder, because they’re shorter and easier to write.
In VS Code, your script is usually in a project folder, so you often use relative paths to point to files in that folder.
We're going to look at multiple ways to do this. No one way is correct (depending on the situation), but there are ways that make your code a lot safer! We will look at using open() and close() as well as something called with()
"filename.txt" is the name (and optionally the path) of the file.
mode tells Python what you want to do with the file (read, write, append, etc.).
The open() function is used to open a file so that you can read, write, or append data.
It returns a file object that you can interact with using methods like .read(), .write(), etc.
As you can see, we have a LOT of different file modes to open a file with!
🧠 Modes like 'rb' or 'wt' can be combined for binary/text operations, though for now we focus on text files.
Remember, when we use VS Code, we will get pop-ups which will help us with the arguments we can use!
Here you see how we can open files in read, write, append, or binary mode. These are typical uses
When we're done processing a file, we need to call the close( ) method!!
This will make sure the file is closed and memory is reclaimed!
Bad things happen when you don't pair open / close together!!!
Yes, There are more arguments we can use, but they're way past the scope of our introductory lesson.
I'll include this so you can see some of what there is, but know that if you want to use them, you'll have to do some research.
But, you really don't need them for now!!
Welcome, Gunter! You’re on a quest in the OASIS, the virtual reality world from Ready Player One, where you need to access secret files to find clues about Halliday’s Easter egg. Your mission is to write a Python program that lets you open a file in the OASIS File Vault and then close it safely—but you’ll need to be careful, because some files might not exist, or the system might glitch!
You’ll ask the user (that’s you, Parzival!) to input the file name and choose how to open it from a menu of modes.
Use your skills with conditionals, loops, functions, and error handling to make sure the OASIS doesn’t crash.
Ready to code your way to the next clue? This should take you 10-20 minutes—let’s dive in!
NOTE: You need to create a file in your VS Code Folder or you'll get an ERROR!!
Get the File Name: Ask the user to input the name of the file they want to access (e.g., clue.txt).
Show a Menu of Modes: Display a menu with three file modes to choose from:
1: Read mode ('r') – Just look at the file.
2: Write mode ('w') – Create or overwrite the file.
3: Append mode ('a') – Add to the file.
Open and Close the File:
Based on the user’s choice, open the file in the selected mode and then close it.
Print a success message like “File accessed successfully in the OASIS!”
Handle Errors: Use try-except to catch two types of errors:
If the file doesn’t exist (FileNotFoundError), print: “Error: That file doesn’t exist in the OASIS!”
If there’s a problem opening the file (general IOError), print: “Error: The OASIS glitched—can’t open the file!”
Loop for Valid Input: If the user enters an invalid mode (e.g., not 1, 2, or 3), keep asking until they pick a valid option.
Use a Function: Put the file-opening logic in a function called access_oasis_file(file_name, mode) to practice using functions.
Here is a sample of what your program could look like. Remember this...
You've played with sounds
You've played with screens
You've done some cool things
Don't forget the Python you've learned!
Once you open the file, you now have a file object which we can do some awesome things with! Remember, the file has to be open to do these. It can't be closed or you'll get errors!!!
The read() method reads the entire content of the file into a single string (or bytes object for binary files).
Usage:
#Read the entire file contents
content = file.read()
#Read up to this many bytes/characters (in this case, 10)
content = file.read(10)
With every read, we MOVE THE FILE POINTER
this is a pointer that tells us where we are in the file.
If we read the whole file (read()), the pointer is at the END OF FILE (EOF)
If we read with (read(10)), the file pointer is at the 11th character
This reads the entire file and prints it out
This reads 5 characters of the file and will print those out
Here we read the first 5 characters
Then, we read the rest of the file
When you do this, you haven't reset the file pointer, so it just keeps moving along with your reads! Be Careful!!
Basic Usage:
Sometimes, the OASIS hides clues across multiple lines in clue_file.txt. With file.readline(), you’re like Parzival reading one scroll at a time.
This method grabs just the next line (including the newline \n), and the file pointer jumps to the start of the next line.
Use a loop to read every line, uncovering secrets one by one—ideal for processing big files without overloading your memory!
This code block shows you how to read the first 2 lines manually
Every call to readline( ) returns a line from the file
This is how we can process all the lines in the file by using a loop
Remember, readline() returns the next line or '' at the end, so when it's the END OF FILE (EOF), the while loop will fail, because there's nothing there!!
file.readlines( ) reads through the file line by line, but instead of needing to process each line, it puts each line in a LIST!!
This is Great for small files you want to analyze line by line, but use it cautiously with huge files to avoid memory crashes!
Once you have the list of lines, you need a for loop to process each one!
Usage is:
list_of_lines = file.readlines()
When you open a file in Python, there's a little "marker" inside the file that keeps track of where you're reading or writing. That marker is called the file pointer
Starting Point:
By default, the pointer starts at the beginning of the file when reading ('r'), and at the end of the file when appending ('a').
End of File:
Once the pointer reaches the end of the file, any further read() calls return an empty string (''), signaling you’ve read everything.
Remember, to move the file pointer to the beginning of a file, just use file.seek(0)
Welcome, Gunter! You’ve just hacked into the OASIS File Vault, a secret directory filled with legendary quotes, powerful artifacts, and the leaderboard of top Egg hunters.
Your task is to build a Python program that lets you interact with this data using menus, searches, and formatting — while defending your code from IOI-level crashes (errors!).
Show a main menu with four options:
Gunter Quotes
Artifact Archive
Leaderboard Legends
Exit the Vault
Allow users to:
View all quotes or search for a phrase in gunter.txt
View artifact names/descriptions or search for a specific item in artifact.txt
Display the leaderboard in table format from leaderboard.txt
Include error handling so your program doesn’t crash if a file is missing
leaderboard.txt
1
parzival
wade watts
2
art3mis
samantha cook
3
Aech
Helen Harris
4
Daito
Toshiro Yoshiaki
5
Sho
Akihide
gunter.txt
“People come to the OASIS for all the things they can do, but they stay for all the things they can be.”
“Reality is the only thing that’s real.”
“You don’t know anything about me, except what I want you to know.”
“A fanboy knows a hater.”
“I don’t like having to fix things. I just like how they were.”
artifact.txt
Item: Zemeckis Cube
Description: A Rubik’s Cube-style artifact that can rewind time by 60 seconds.
Item: Holy Hand Grenade
Description: A deadly explosive from Monty Python and the Holy Grail. Used by Aech in the final battle.
Item: Orb of Osuvox
Description: A magical orb that casts a force field around Castle Anorak
Item: Cataclyst Bomb
Description: Destroys everyone in the OASIS
Create a loop-driven menu with these options:
1: Gunter Quotes
Display all five quotes, one per line.
Handle errors if the file’s missing—don’t let IOI ruin your day!
Let users search for a word or phrase (case-insensitive) and show if it’s in any quote.
2: Artifact Archive
Show all four artifacts with their descriptions, formatted nicely (e.g., “Item: [name] – [description]”).
Allow a search by item name (e.g., “Zemeckis Cube”) and display its description if found.
Catch errors if the file’s gone AWOL.
3: Leaderboard Legends
Display the leaderboard as a table with rank, username, and real name for all five entries.
Use readlines() to grab the data in groups of three lines.
Handle errors if the file’s corrupted or missing.
4: Exit the Vault
Use readlines() for reading all lines into a list.
Use .lower() to make case-insensitive searches.
Use a while True: loop with break conditions for menus.
Format your output neatly — make it look pro.
Test each part as you go so bugs don’t sneak up on you like IOI drones.