Exceptions & Files · Question 12 · Medium

read() is called three times on the same file-like object, first with a size. What do the three results look like?

import io

f = io.StringIO("hello")
a = f.read(2)
b = f.read()
c = f.read()
print(a, b, repr(c))
  1. he hello ''
  2. he llo ''
  3. he llo None
  4. he llo llo
Answer and explanation

Answer: B. he llo ''

Explanation: The file position moves forward as you read. read(2) returns he, the next read() returns the rest (llo), and a read at the end of a file returns an empty string, not None.

Previous: Lines of numbers are read from a file-like object inside a with block and… · Next: Why is with open("data.txt") as f: preferred over calling open() and close()…

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