Using standard library codecs modules
Codecs.open (filename, mode= ' R ', Encoding=none, errors= ' strict ', buffering=1)
1 import codecs2 f = codecs.open (filename, encoding= ' utf-8 ')
Read the Utf-8 file in this way above and automatically convert to Unicode. However, it must be clear that the file type is UTF8 type. If there is a Chinese character in the file, it is not a byte to read but all the bytes of the whole Chinese character are read in and converted to Unicode (conjecture is related to the UTF8 encoding of Chinese characters).
The code below is also a way to read and write using codecs
#coding =utf-8import codecsfin = open ("Test.txt", ' r ') Fout = open ("Utf8.txt", ' w ') reader = Codecs.getreader (' GBK ') (Fin) writer = Codecs.getwriter (' GBK ') (fout) data = Reader.read #10是最大字节数, the default value is 1, which means as large as possible. You can avoid processing large amounts of data at one time while data: writer.write (data) Data = Reader.read (10)
Python character encoding