Bird
0
0

What will be the output of this code snippet reading a file in fixed-size chunks?

medium📝 Predict Output Q4 of 15
Python - File Reading and Writing Strategies

What will be the output of this code snippet reading a file in fixed-size chunks?

with open('sample.txt', 'r') as f:
    while True:
        data = f.read(4)
        if not data:
            break
        print(data, end='-')
ARaises an error due to incorrect read size
BPrints the entire file content at once
CPrints nothing because of an infinite loop
DPrints the file content in 4-character chunks separated by '-'
Step-by-Step Solution
Solution:
  1. Step 1: Read fixed-size chunks

    The code reads 4 characters at a time from the file until no data is left.
  2. Step 2: Print chunks with separator

    Each chunk is printed followed by a '-', so output shows file content in 4-char segments separated by '-'.
  3. Final Answer:

    Prints the file content in 4-character chunks separated by '-' -> Option D
  4. Quick Check:

    Reads 4 chars repeatedly until EOF [OK]
Quick Trick: Read fixed-size chunks and print until empty [OK]
Common Mistakes:
  • Assuming read() returns lines instead of characters
  • Missing break causes infinite loop
  • Thinking print outputs whole file at once

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes