Challenge - 5 Problems
File Reading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of reading a file with read()?
Consider a file named
example.txt containing the text Hello World!. What will be the output of this code?Python
with open('example.txt', 'r') as file: content = file.read() print(content)
Attempts:
2 left
💡 Hint
The read() method reads the whole file as one string.
✗ Incorrect
The read() method returns the entire content of the file as a single string exactly as it is stored. Since the file contains 'Hello World!' on one line, the output is that string.
❓ Predict Output
intermediate2:00remaining
What happens if you read a file twice without resetting?
Given a file
data.txt with content abc, what will be printed by this code?Python
with open('data.txt', 'r') as f: first = f.read() second = f.read() print(first) print(second)
Attempts:
2 left
💡 Hint
After reading once, the file pointer is at the end.
✗ Incorrect
The first read() reads all content 'abc'. The second read() returns an empty string because the file pointer is at the end of the file.
❓ Predict Output
advanced2:00remaining
What is the output of reading a binary file as text?
Assuming
binary.dat contains bytes \x48\x65\x6c\x6c\xff, what happens when running this code?Python
with open('binary.dat', 'r') as f: content = f.read() print(content)
Attempts:
2 left
💡 Hint
Opening a binary file in text mode may cause decoding errors.
✗ Incorrect
Opening a binary file in text mode tries to decode bytes as UTF-8 by default. If bytes are invalid UTF-8, a UnicodeDecodeError is raised.
❓ Predict Output
advanced2:00remaining
What is the output when reading a file with read(size)?
Given a file
text.txt containing Python, what will this code print?Python
with open('text.txt', 'r') as f: part = f.read(3) rest = f.read() print(part) print(rest)
Attempts:
2 left
💡 Hint
read(3) reads first 3 characters, next read() reads the rest.
✗ Incorrect
The first read(3) reads 'Pyt'. The file pointer moves forward. The next read() reads the remaining 'hon'.
🧠 Conceptual
expert2:00remaining
Why is it important to use 'with' when reading files?
Which option best explains the advantage of using
with open(...) to read files?Attempts:
2 left
💡 Hint
Think about what happens to the file after reading is done.
✗ Incorrect
Using 'with' ensures the file is closed automatically after the block ends, even if errors occur. This prevents resource leaks and is good practice.