Challenge - 5 Problems
File Reading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Reading lines from a file
What is the output of this code when reading lines from a file named
Line1
Line2
Line3?
example.txt containing three lines: Line1
Line2
Line3?
Python
with open('example.txt', 'r') as file: lines = file.readlines() print(len(lines))
Attempts:
2 left
💡 Hint
The
readlines() method returns a list of all lines in the file.✗ Incorrect
The file has three lines, so
readlines() returns a list with three elements. The length is 3.❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
The
read() method returns the whole file content as a string including newlines.✗ Incorrect
The
read() method reads the entire file as a string, preserving newlines.❓ Predict Output
advanced2: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())
Attempts:
2 left
💡 Hint
The loop reads each line and
strip() removes the newline before printing.✗ Incorrect
Each line is printed on its own line without trailing newline characters.
❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
The
read(4) reads only the first 4 characters.✗ Incorrect
The
read(4) reads exactly 4 characters from the file.🧠 Conceptual
expert2: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')
Attempts:
2 left
💡 Hint
The specific error for missing files is
FileNotFoundError.✗ Incorrect
Trying to open a non-existent file raises
FileNotFoundError in Python 3.