Bird
0
0

What will be the output of this code snippet when reading a large file in chunks?

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

What will be the output of this code snippet when reading a large file in chunks?

with open('largefile.txt', 'r') as f:
    chunk = f.read(5)
    print(chunk)
    chunk = f.read(5)
    print(chunk)
APrints first 5 characters, then next 5 characters of the file
BPrints the entire file twice
CPrints only the first 5 characters twice
DRaises an error because read() needs no arguments
Step-by-Step Solution
Solution:
  1. Step 1: Understand read(size) behavior

    Calling f.read(5) reads 5 characters from the current file position.
  2. Step 2: Reading twice moves file pointer forward

    First read gets chars 1-5, second read gets chars 6-10.
  3. Final Answer:

    Prints first 5 characters, then next 5 characters of the file -> Option A
  4. Quick Check:

    read(5) reads 5 chars sequentially [OK]
Quick Trick: read(n) reads next n characters sequentially [OK]
Common Mistakes:
  • Thinking read() reads whole file always
  • Assuming read(5) resets file pointer
  • Believing read() without args is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes