如何读取中文txt文件(Python)

Bry*_*hai 6 python decode file utf-8 python-3.x

我有一个名为“chinchars.txt”的 .txt 文件。在里面,我有一行包含这两个字符:

\n\n

\xe8\x8a\x82\xe6\x97\xa5

\n\n

我如何读取这个文本文件并将其返回给字符?\n使用此代码:

\n\n
inputFile = open(\'chinchars.txt\').readlines()\n
Run Code Online (Sandbox Code Playgroud)\n\n

它输出这个错误:

\n\n
UnicodeDecodeError: \'charmap\' codec can\'t decode byte 0x8f in position \n18: character maps to <undefined>\n
Run Code Online (Sandbox Code Playgroud)\n\n

我相信我需要以某种方式“解码”这些字符。这将如何实现?

\n

Meh*_*far 3

试试这个,它可能对你有帮助:

inputFile = open('chinchars.txt', encoding="utf8").readlines()
Run Code Online (Sandbox Code Playgroud)

请注意,最好使用with. 像这样:

with open('chinchars.txt', encoding="utf8") as f:
    inp = f.readlines()
Run Code Online (Sandbox Code Playgroud)

  • @DyZ我很确定文本流(`sys.std*`、`open`)的默认值在Python 3中是依赖于语言环境/平台的。编码默认为UTF-8,仅适用于源编码和`str。编码/解码`。 (2认同)