我正在使用下面的代码,但需要打开它以指定 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', buffering=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.
关于python - 使用UTF-8打开文件进行读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21756347/