Library contents

Python ValueError on a closed stream

Reading from a closed StringIO stream raises ValueError. Use a new stream or keep the original open for the full preview operation.

A simple example

ValueError on a closed stream

  1. Start with A reader has already been closed
  2. Do this Try another read
  3. Result Read fails
Closing a stream ends its usable lifetime. A new reader is needed for another read.

Syntax

Python syntax
reader.readline()
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Read from a finished receipt import

A receipt importer closes its reader at the end of a batch. If the preview screen asks for another line through that reader, the application needs to detect the stale handle and open a new reader for the next batch.

ResultOpen a new reader
lesson.py
from io import StringIO

reader = StringIO("Receipt 42")
reader.close()
try:
    print(reader.readline())
except ValueError:
    print("Open a new reader")
Output
Open a new reader

The importer closed this reader before the preview tried to read. A fresh reader is needed for another pass.

Advertisements

Read the first rehearsal note

The music desk has just opened a reader containing a short note. Read the next character from the stream. A previously closed stream prompts the desk to reopen the source.

GivenOpen reader · “Tune”
Worked resultRead succeeded

Revisit a completed import

A receipt reader was closed before the operator requested the next character. Read the next character from the stream. A previously closed stream prompts the desk to reopen the source.

GivenClosed reader
Worked resultReopen source

What to watch for

An empty line at the end of an open stream is a normal end condition. A closed stream has finished its lifecycle.

Documentation for ValueError on a closed stream