【发布时间】:2017-03-30 00:59:43
【问题描述】:
我目前的 python 3 代码有问题。
replace_line('Products.txt', line, tenminus_str)
是我试图转换为 utf-8 的行,但是当我尝试像对待其他人一样执行此操作时,我会收到诸如无属性错误之类的错误,并且当我尝试添加时,例如...
.decode("utf8")
...到最后,我仍然收到它使用 ascii 的错误。我还尝试了与其他行一起使用的其他方法,例如添加 io.在前面并用
添加逗号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
这是什么意思,我该如何解决?
【问题讨论】:
-
向我们展示您的 stracktrace,向我们展示您的数据
-
什么意思?
-
使用 utf_8_sig,而不是 utf8,您的文件可能以 bom 开头
-
.decode('utf_8_sig')
-
decode('utf8', errors='ignore')
标签: python unicode utf-8 ascii