When code must read different kinds of files without handling each implementation separately, a file-like object provides a shared file operation API. Python's open function can return objects such as TextIOWrapper or BufferedReader, while buffering and filesystem differences remain behind that interface. section 5.2
Use the interface in several practical ways:
- Iterate over a file-like object to receive one line at a time, including its trailing newline. section 5.2
- Iterate directly over open(filename) when the file will be consumed only once. section 5.2
- Use StringIO when code needs file operations without touching the filesystem, especially in automated tests. section 5.3
Reading simulated file content
from io import StringIO f = StringIO('first line\nlast line\n') final_line = '' for current_line in f: final_line = current_line print(final_line) section 5.3
with open(filename) as f:
for one_line in f:
print(len(one_line))
Compare context-managed reading with direct iteration, while retaining the same file-like interface. section 5.2

