all Python 3codecsterm
codecs.StreamWriter
stream codecs
The base class of stream encoders: it wraps a binary stream, and write(str) encodes the text and writes bytes. codecs.getwriter returns a ready subclass.
Syntax
writer = codecs.getwriter(encoding)(stream, errors='strict')
The classic case is sys.stdout.buffer in old code: codecs.getwriter('utf-8')(sys.stdout.buffer). Today sys.stdout.reconfigure(encoding='utf-8') or io.TextIOWrapper does the same and, unlike StreamWriter, handles buffering and newline translation properly. The underlying stream is available as .stream; closing the wrapper closes it too.
Examples
import codecs, io
w = codecs.getwriter('cp1251')(io.BytesIO())
w.write('ёж')
print(w.stream.getvalue()) # → b'\xb8\xe6'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy