0
0
Pythonprogramming~20 mins

Reading files line by line in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Reader Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A['line1', 'line2', 'line3']
B[' line1 ', 'line2', ' line3 ']
C['line1 ', 'line2', 'line3 ']
D[' line1', 'line2', ' line3']
Attempts:
2 left
💡 Hint
The strip() method removes spaces at the start and end of each line.
Predict Output
intermediate
2: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)
A['apple banana cherry']
B['apple\n', 'banana\n', 'cherry\n']
C['apple', 'banana', 'cherry']
D['apple\r\n', 'banana\r\n', 'cherry\r\n']
Attempts:
2 left
💡 Hint
readlines() keeps the newline characters at the end of each line.
🔧 Debug
advanced
2: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()
ATypeError because file is not iterable
BSyntaxError because the for loop is missing a colon
CFileNotFoundError because the file 'missing.txt' does not exist
DIndentationError because print is not indented
Attempts:
2 left
💡 Hint
Check if the file exists before opening it.
Predict Output
advanced
2: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)
A['one', 'two', 'three']
B['one\ntwo\nthree\n']
C['one', 'two', 'three', '']
D['one', 'two', 'three', None]
Attempts:
2 left
💡 Hint
readline() returns an empty string when the file ends.
Predict Output
expert
2: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)
A1
B4
C2
D3
Attempts:
2 left
💡 Hint
Count lines except those equal to 'b' after stripping.