A file-like object provides a file-style interface for reading, writing, or iteration, even when its underlying implementation differs. Python uses this common API to hide filesystem differences and expose optimizations such as buffering. section 6.3
Use file-like objects through familiar Python operations:
- Iterate over an object to receive successive lines, including their newline characters. section 6.3
- Call open with read, write, append, text, or binary modes; binary iteration yields bytes rather than text lines. section 6.3
- Use a context manager when processing an opened object, or read binary data in fixed-size chunks until no data remains. section 6.3
Testing without filesystem access
StringIO implements the file API while keeping data in memory, so tests can simulate files without touching the filesystem. section 6.4
with open(filename) as f:
for one_line in f:
print(len(one_line))
This pattern demonstrates opening a file-like object with a context manager and iterating through its lines. section 6.3

