Reading and searching files
Open files in "r" (read) mode to access their contents. If you’ve just written to a file, ensure it’s closed before re-opening it for reading.
Read a file line by line
Use a context manager so the file closes automatically:
# Open the file in read mode and print each line
with open("Customers.txt", "r") as file:
for line in file:
print(line, end="")
Practice Task 1: Display file contents
Task 1: Read and print a file
Open one of the files you created earlier and print each line without adding extra spaces.
Show sample solution
# Read and display the contents of "MyFriends.txt"
with open("MyFriends.txt", "r") as friend_file:
for line in friend_file:
print(line, end="")
Reading specific lines
Load all lines into a list and then access by index (remember: indexing starts at 0!):
# Read all lines into a list
with open("Advice.txt", "r") as advice_file:
advice_lines = advice_file.readlines()
# Prompt user for a line number (1-based)
line_number = int(input("Enter a number between 1 and " + str(len(advice_lines)) + ": "))
print("Your selected advice:", advice_lines[line_number - 1], end="")
Practice Task 2: Video Game Selector
Task 2: Read a specific line from a file
Create a Games.txt with one game per line. Ask the user for a number between 1 and the number of games, then display that game.
Show sample solution
# Read the list of video games from Games.txt
with open("Games.txt", "r") as games_file:
games = games_file.readlines()
# Get user input and print the corresponding game (adjust for 0-based index)
choice = int(input("Enter a number between 1 and " + str(len(games)) + ": "))
print("You selected:", games[choice - 1].strip())
Searching through a file
To perform a case-insensitive search, compare lowercase versions of both the search term and each line:
# Prompt user for a search term
search_term = input("Enter a search term: ")
found = False
with open("Customers.txt", "r") as file:
for line in file:
if search_term.lower() in line.lower():
print(line, end="")
found = True
if not found:
print("No matches found for", search_term)
Practice Task 3: Search for a student record
Task 3: Extend the ALevels file
Using ALevels.txt from the previous task, ask for a student name and print the matching line if found.
Show sample solution
# Search for a student record in ALevels.txt
student_name = input("Enter a student's name to search for: ")
record_found = False
with open("ALevels.txt", "r") as file:
for line in file:
if student_name.lower() in line.lower():
print("Record found:", line.strip())
record_found = True
break
if not record_found:
print("No record found for", student_name)
Tips & good practice
- Use a
with open(...)block so files always close—even if an error happens. readlines()gives you a list; each item usually ends with\n— use.strip()when printing.- For big files, loop over the file object instead of loading everything into memory.
- Do case-insensitive matching by comparing
.lower()versions.