Anatomy of File Iteration
A more Pythonic way to read lines is by iterating directly over the file object. Let's dissect this efficient pattern, including stripping whitespace. Click each part.
with open('logs.txt', 'r') as infile:
for line in infile:
print(line.strip())
Identify all parts!
Build a File Loop
Drag the pieces to construct a Python loop that opens `config.cfg`, iterates through each `line`, and prints the line without leading/trailing whitespace.
Error Handling Simulator
What happens if a file doesn't exist? Use `try...except FileNotFoundError` to handle this gracefully. Edit the code to safely read `maybe.txt` and print its content OR print an error message if it's missing. Use the button to toggle if the file "exists".
Concept Check
Let's check your understanding of some key file handling concepts. Choose the best answer(s).
Advanced Mini Missions!
Time for some more complex tasks involving iteration, processing, and error handling.
Mission 1: Summing Numbers
Read numbers.txt
line by line. Each line contains a number. Convert each line to an integer (after stripping whitespace!) and calculate the total sum. Print only the final sum.
numbers.txt
Mission 2: Count Specific Lines
Read words.txt
line by line. Count how many lines contain the word "AI" (case-sensitive). Print only the final count.
words.txt
Mission 3: Safe Read
Attempt to open and read the entire content of secret.txt
. If the file exists, print its content. If it doesn't exist, print the exact message: Secret file not found.
Use `try...except FileNotFoundError`.
secret.txt
(Sometimes Exists!)
[Content hidden unless file exists]
Module 23 Advanced Practice Complete!
Fantastic! You've tackled more advanced file reading techniques, including iteration and error handling. Persistence pays off!
Feel free to review the Video Lesson or head back to the Course Menu.