all Python 3codecsfunction
codecs.getwriter()
stream codecs
Returns the StreamWriter class for an encoding; call it with a binary stream to get an object you write str to.
Syntax
writer = codecs.getwriter(encoding)(stream)
As with getreader, the result is a class, not a ready writer. Wrap a binary stream: open(path, 'wb'), io.BytesIO or sys.stdout.buffer. Wrapping the text sys.stdout makes writes fail with TypeError. To change stdout's encoding, since 3.7 sys.stdout.reconfigure(encoding='utf-8') is simpler.
Examples
import codecs, io
buf = io.BytesIO()
Writer = codecs.getwriter('utf-8')
Writer(buf).write('я')
print(buf.getvalue()) # → b'\xd1\x8f'
print(Writer is codecs.lookup('utf-8').streamwriter) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy