Lesson contents

Python — Reading text with a context manager

A Python with statement manages an open file for the duration of its block. After writing, seek back to the start to read the same file before the block closes it.

A simple example

Read back one letter

  1. Start with A
  2. Do this Write, then read
  3. Result A
A file stores the letter between the write and the read.
lesson.py
from tempfile import TemporaryFile

with TemporaryFile(mode="w+") as file:
    file.write("A")
    file.seek(0)
    print(file.read())
Output
A
Advertisements

Sum two lines from a temporary report

The with statement closes the temporary file on exit. The seek resets the cursor. The generator expression reads nonblank lines one at a time, so the sum does not need a list of all readings.

Morning returns: 4. Afternoon returns: 7. End of day: 11.
Read a two-line count sheet

Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.

Run the example

Python 3.8 or later. Run these commands from the directory containing the example.

python3 lesson.py
lesson.py
from tempfile import TemporaryFile

with TemporaryFile(mode="w+t", encoding="utf-8") as report:
    report.write("4\n7\n")
    report.seek(0)
    total = sum(int(line) for line in report if line.strip())
print(total)
Output
11

The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.

Try it yourself

Add a third line containing 12.

Check your answer

The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.

The Python Tutorial

Related tags

  • Python
  • files
  • streams
  • resource management