Exceptions & Files · Question 20 · Hard

Two lines are written to an in-memory text file, which is read once before and once after seek(0). What is printed?

import io

buf = io.StringIO()
buf.write("pune\n")
buf.write("kochi\n")
first = buf.read()
buf.seek(0)
print(repr(first), buf.read().split())
  1. '' ['pune', 'kochi']
  2. 'pune\nkochi\n' ['pune', 'kochi']
  3. '' []
  4. 'pune\n' ['kochi']
Answer and explanation

Answer: A. '' ['pune', 'kochi']

Explanation: After the two writes the position is at the end, so the first read() finds nothing and returns ''. seek(0) moves back to the start, and the second read() returns everything, which split() breaks into the two words.

Previous: Which of these exceptions is NOT caught by a handler written as except…

Practise exceptions & files

Try a fresh set of exceptions & files questions with an explanation after every answer, free and without signing up: Exceptions & Files practice. Or sit a full placement mock test.

More exceptions & files questions

More python practice

Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope · Comprehensions & Generators

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge