read() retrieves the contents available through an open file handle. Calling fh.read() returns the entire text as one string, so the file must fit in available memory. section 5.1 section 5.5.2
Use read() with these practical behaviors:
- Open a path first, then call fh.read(); os.path.isfile() can check that the path exists before opening it. section 5.1
- Reading consumes the handle: a second fh.read() returns an empty string. Use fh.seek(0) to return to the beginning. section 5.1
- Strip a trailing newline when normalizing file input with open(file).read().rstrip(). section 5.5.2
- Prefer iteration over the file handle for large files, processing one line at a time instead of loading everything. section 6.1.2
Read and normalize a text file
file = 'inputs/fox.txt' if os.path.isfile(file): text = open(file).read().rstrip() print(text) # The quick brown fox jumps over the lazy dog. section 5.1 section 5.5.2
Trace the exercise that accepts either literal input or a filename, then reads and normalizes the file contents. section 5.1



