Python:UnicodeDecodeError:“ascii”编解码器无法解码位置 0 中的字节 0xef:序号不在范围内(128)

Nam*_*und 2 python unicode ascii utf-8

我目前的 python 3 代码有问题。

 replace_line('Products.txt', line, tenminus_str)
Run Code Online (Sandbox Code Playgroud)

是我试图变成 utf-8 的行吗,但是当我尝试像其他人一样这样做时,我会收到错误,例如没有属性,并且当我尝试添加时,例如...

.decode("utf8")
Run Code Online (Sandbox Code Playgroud)

...到最后,我仍然收到它使用 ascii 的错误。我还尝试了与其他行一起使用的其他方法,例如添加 io. infront 并添加一个逗号

encoding = 'utf8'
Run Code Online (Sandbox Code Playgroud)

我用于 replace_line 的函数是:

def replace_line(file_name, line_num, text):
    lines = open(file_name, 'r').readlines()
    lines[line_num] = text
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()
Run Code Online (Sandbox Code Playgroud)

我将如何解决这个问题?请注意,我对 Python 非常陌生,还不够先进,无法很好地进行调试。

编辑:与“重复”不同的解决此问题的方法

编辑 2:我现在有另一个功能错误。

File "FILELOCATION", line 45, in refill replace_line('Products.txt', str(line), tenminus_str) 

File "FILELOCATION", line 6, in replace_line lines[line_num] = text

TypeError: list indices must be integers, not str 
Run Code Online (Sandbox Code Playgroud)

这是什么意思,我该如何解决?

Mar*_*nen 5

将您的功能更改为:

def replace_line(file_name, line_num, text):
    with open(file_name, 'r', encoding='utf8') as f:
        lines = f.readlines()
    lines[line_num] = text
    with open(file_name, 'w', encoding='utf8') as out:
        out.writelines(lines)
Run Code Online (Sandbox Code Playgroud)

encoding='utf8' 将正确解码您的 UTF-8 文件。

with 退出块时自动关闭文件。

由于您的文件以\xef它开头,因此开头可能有一个 UTF-8 编码的字节顺序标记 (BOM) 字符。上面的代码将在输出中保持它,但如果您不希望它utf-8-sig用于输入编码。然后它会被自动删除。