Python读取中文txt文件错误:UnicodeEncodeError: 'gbk' codec can't encode character
1 with open(file,'r') as f: 2 line=f.readline() 3 i=1 4 while line: 5 line=line.decode('utf-8') 6 print str(i)+": "+line7 line=f.readline() 8 i=i+1
用以上代码读取一个包含中文的txt文件时,在正确地读取并打印了六百多行之后,print str(i)+": "+line这一行报错:
UnicodeEncodeError: 'gbk' codec can't encode character u'\u200b' in position 99: illegal multibyte sequence
上网查到http://www.crifan.com/unicodeencodeerror_gbk_codec_can_not_encode_character_in_position_illegal_multibyte_sequence/
据分析,上述代码先decode方法将中文字符转为unicode编码,然后print语句打印时,会将其以默认的gbk进行编码,前六百多行能正确打印,说明能够正常编码成gbk,但存在部分字符不能用gbk编码,改用比gbk更大的字符集gb18030之后就没问题了:
1 print str(i)+": "+line
改为:
1 print str(i)+" "+line.encode('gb18030')