2

我正在使用下面的代码,但需要打开它以指定 utf-8 进行阅读。请问我该怎么做?

infile = file(logPath)
lines = infile.readlines()
4

1 回答 1

3

codecs模块的使用open功能:

import codecs

with codecs.open(logPath, encoding='utf8') as infile:
    lines = infile.readlines()

默认情况下,以(读取二进制)模式codecs.open打开文件:rb

def open(文件名,模式='rb',编码=无,错误='严格',缓冲=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.
于 2014-02-13T14:01:45.453 回答