2

以下のコードを使用していますが、utf-8 を指定して読み取るために開く必要があります。どうすればいいですか?

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

1 に答える 1

3

コーデックモジュールの使用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.
于 2014-02-13T14:01:45.453 に答える