codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' 编解码器无法解码位置 318 中的字节0xc2:序号不



我正在尝试打开并读取包含大量文本的.txt文件。下面是我的代码,我不知道如何解决这个问题。任何帮助将不胜感激。

file = input("Please enter a .txt file: ")
myfile = open(file)
x = myfile.readlines()
print (x)

当我输入.txt文件时,这是完整的错误消息,如下所示:

line 10, in <module> x = myfile.readlines()
line 26, in decode return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 318: ordinal not in range(128)

我没有使用编解码器,而是这样解决它:

def test():
    path = './test.log'
    file = open(path, 'r+', encoding='utf-8')
    while True:
        lines = file.readlines()
        if not lines:
            break
        for line in lines:
            print(line)

您必须精确地给出编码参数。

您也可以尝试编码:

with open(file) as f:
    for line in f: 
         line = line.encode('ascii','ignore').decode('UTF-8','ignore')
         print(line)

@AndriiAbramamov是对的,你应该检查这个问题,这里有一种方法可以打开你的文件,该文件也在那个链接上

import codecs
f = codecs.open('words.txt', 'r', 'UTF-8')
for line in f:
    print(line)

另一种方法是使用正则表达式,因此当您打开文件时,您可以删除任何特殊字符,例如双引号等。

相关内容

最新更新