【发布时间】:2014-02-13 13:59:47
【问题描述】:
我正在使用下面的代码,但需要打开它以指定 utf-8 进行阅读。请问我该怎么做?
infile = file(logPath)
lines = infile.readlines()
【问题讨论】:
我正在使用下面的代码,但需要打开它以指定 utf-8 进行阅读。请问我该怎么做?
infile = file(logPath)
lines = infile.readlines()
【问题讨论】:
使用codecs模块的open函数:
import codecs
with codecs.open(logPath, encoding='utf8') as infile:
lines = infile.readlines()
默认codecs.open函数,以rb(读取二进制)模式打开文件:
def open(filename, mode='rb', encoding=None, errors='strict', 缓冲=1):
... Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8-bit values. The default file mode is 'rb' meaning to open the file in binary read mode.
【讨论】: