liveBook · Manning

Read operation

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

file.read() reads data from a file object and returns it as a string or bytes according to the file mode.

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

This is our first exercise that will involve reading files. The argument to the program will be some text that might name an input file, in which case you will open and read the file. If the text is not the name of a file, you’ll use the text itself.


Trace the exercise that accepts either literal input or a filename, then reads and normalizes the file contents. section 5.1

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains whole-file retrieval, handle exhaustion, resetting, whitespace normalization, and line iteration for large files.
Examples
Demonstrates inputs/fox.txt, chained open(file).read().rstrip(), repeated reads, and nested loops over files and lines.
What it assumes
Assumes basic Python and command-line arguments while teaching file existence checks, opening handles, reading, and normalization.
What you can do after
Apply it via Python to load small files, normalize their text, or process larger files incrementally by line.
How it connects
Connects read() with open(), file handles, os.path.isfile(), str.rstrip(), command-line arguments, and file iteration.

Also explained in

Compare how 3 books explain read operation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.