Challenge - 5 Problems
File Reader Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of reading lines with strip()
What is the output of this Python code that reads a file line by line and strips whitespace?
Python
with open('test.txt', 'w') as f: f.write(' line1 \nline2\n line3 \n') with open('test.txt', 'r') as file: lines = [line.strip() for line in file] print(lines)
Attempts:
2 left
💡 Hint
The strip() method removes spaces at the start and end of each line.
✗ Incorrect
Using line.strip() removes all leading and trailing spaces from each line, so the list contains clean strings without extra spaces.
❓ Predict Output
intermediate2:00remaining
Reading file lines with readlines()
What will be the output of this code that reads lines from a file using readlines()?
Python
with open('test2.txt', 'w') as f: f.write('apple\nbanana\ncherry\n') with open('test2.txt', 'r') as f: fruits = f.readlines() print(fruits)
Attempts:
2 left
💡 Hint
readlines() keeps the newline characters at the end of each line.
✗ Incorrect
The readlines() method returns a list of lines including the newline characters '\n' at the end of each line.
🔧 Debug
advanced2:00remaining
Why does this code raise an error?
This code tries to read a file line by line but raises an error. What is the cause?
Python
file = open('missing.txt', 'r') for line in file: print(line) file.close()
Attempts:
2 left
💡 Hint
Check if the file exists before opening it.
✗ Incorrect
Trying to open a file that does not exist in read mode causes a FileNotFoundError.
❓ Predict Output
advanced2:00remaining
Output of reading file with a while loop
What is the output of this code that reads a file line by line using a while loop?
Python
with open('test3.txt', 'w') as f: f.write('one\ntwo\nthree\n') with open('test3.txt', 'r') as f: line = f.readline() lines = [] while line: lines.append(line.strip()) line = f.readline() print(lines)
Attempts:
2 left
💡 Hint
readline() returns an empty string when the file ends.
✗ Incorrect
The loop reads each line until readline() returns an empty string, stripping spaces and newlines, so the list contains clean lines.
❓ Predict Output
expert2:00remaining
Number of lines read with a generator expression
What is the number of lines read by this code using a generator expression?
Python
with open('test4.txt', 'w') as f: f.write('a\nb\nc\nd\n') with open('test4.txt', 'r') as f: count = sum(1 for _ in f if _.strip() != 'b') print(count)
Attempts:
2 left
💡 Hint
Count lines except those equal to 'b' after stripping.
✗ Incorrect
The generator counts lines where the stripped line is not 'b'. Lines are 'a', 'b', 'c', 'd', so count is 3.