Skip to main content
 首页 » 编程设计

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

2025年05月04日13emanlee

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

 replace_line('Products.txt', line, tenminus_str) 

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

.decode("utf8") 

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

encoding = 'utf8' 

我为 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() 

我该如何解决这个问题?请注意,我是 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  

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

请您参考如下方法:

将您的功能更改为:

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) 

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

with 在退出 block 时自动关闭文件。

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