0
0
Pythonprogramming~20 mins

Reading file data in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Reading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Reading lines from a file
What is the output of this code when reading lines from a file named example.txt containing three lines:
Line1
Line2
Line3?
Python
with open('example.txt', 'r') as file:
    lines = file.readlines()
print(len(lines))
A0
B1
C3
DRaises FileNotFoundError
Attempts:
2 left
💡 Hint
The readlines() method returns a list of all lines in the file.
Predict Output
intermediate
2:00remaining
Reading file content with read()
What will be printed by this code if data.txt contains the text Hello\nWorld?
Python
with open('data.txt', 'r') as f:
    content = f.read()
print(content)
ARaises TypeError
BHello World
C['Hello', 'World']
D
Hello
World
Attempts:
2 left
💡 Hint
The read() method returns the whole file content as a string including newlines.
Predict Output
advanced
2:00remaining
Reading file with a loop
What is the output of this code snippet reading notes.txt with 2 lines: Note1 and Note2?
Python
with open('notes.txt', 'r') as file:
    for line in file:
        print(line.strip())
A
Note1
Note2
B['Note1', 'Note2']
CNote1 Note2
DRaises AttributeError
Attempts:
2 left
💡 Hint
The loop reads each line and strip() removes the newline before printing.
Predict Output
advanced
2:00remaining
Reading file with read(size)
What will this code print if file.txt contains abcdefg?
Python
with open('file.txt', 'r') as f:
    part = f.read(4)
    print(part)
Aabcdefg
Babcd
Cabc
DRaises ValueError
Attempts:
2 left
💡 Hint
The read(4) reads only the first 4 characters.
🧠 Conceptual
expert
2:00remaining
File reading error handling
Which option correctly handles the error if the file missing.txt does not exist when trying to read it?
Python
try:
    with open('missing.txt', 'r') as f:
        data = f.read()
except ???:
    print('File not found')
AFileNotFoundError
BIOError
CValueError
DKeyError
Attempts:
2 left
💡 Hint
The specific error for missing files is FileNotFoundError.