March 2003
Intermediate to advanced
656 pages
39h 30m
English
EncodedFile
EncodedFile(file,datacodec,filecodec=None,errors=’strict')
Wraps the file-like object file, returning
another file-like object ef that
implicitly and transparently applies the given encodings to all data
read from or written to the file. When you write a string
s to ef,
ef first decodes
s with the codec named by
datacodec, then encodes the result with
the codec named by filecodec, and lastly
writes it to file. When you read a string,
ef applies
filecodec first, then
datacodec. When
filecodec is None,
ef uses
datacodec for both steps in either
direction.
For example, if you want to write strings that are encoded in
latin-1 to sys.stdout and have
the strings come out in utf-8, use the following:
import sys, codecs
sys.stdout = codecs.EncodedFile(sys.stdout,'latin-1',
'utf-8')Read now
Unlock full access