Fix the File Reading Bug
Intermediate · Fix the bug · from Python File Handling: Read, Write, and Process Files
From the lesson: Python File Handling: Read, Write, and Process Files
Imagine you have a notebook where you write down important things. You open it, read what's inside, add new notes, and then close it. Python works with files the same way.
Read the lessonThis code tries to read a file twice, but the second read returns an empty string. Fix the bug so both reads print the file content.
Expected output:
First read: hello
Second read: helloimport io
f = io.StringIO('hello')
first = f.read()
print(f'First read: {first}')
# Bug: second read returns empty string
second = f.read()
print(f'Second read: {second}')
f.close()
More File Handling exercises
- Read and Print File ContentsBeginner
- Predict the Read OutputBeginner
- Write and Read BackIntermediate
- Line Number FormatterAdvanced
All Python exercises · 50 practice problems · File I/O & Data Formats quiz