问题描述
我的python 3代码目前有问题.
I'm currently have an issue with my python 3 code.
replace_line('Products.txt', line, tenminus_str)
这是我要转换为utf-8的行,但是,当我尝试像与其他人一样执行此操作时,会出现诸如无属性的错误以及尝试添加时的错误……
Is the line I'm trying to turn into utf-8, however when I try to do this like I would with others, I get errors such as no attribute ones and when I try to add, for example...
.decode("utf8")
...到最后,我仍然收到它正在使用ascii的错误.我还尝试了与其他行一起使用的其他方法,例如添加io. infront并用
...to the end of it, I still get errors that it is using ascii. I also tried other methods that worked with other lines such as adding io. infront and adding a comma with
encoding = 'utf8'
我用于replace_line的函数是:
The function that I am using for replace_line is:
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的新手,不够先进,无法很好地进行调试.
How would I fix this issue? Please note that I'm very new to Python and not advanced enough to do debugging well.
与重复"不同,此问题的解决方案
Different fix to this question than 'duplicate'
我现在对该函数有另一个错误.
EDIT 2:I have another error with the function now.
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
这是什么意思,我该如何解决?
What does this mean and how do I fix it?
推荐答案
codecs
模块正是您所需要的. 详细信息此处
codecs
module is just what you need. detail here
import codecs
def replace_line(file_name, line_num, text):
f = codecs.open(file_name, 'r', encoding='utf-8')
lines = f.readlines()
lines[line_num] = text
f.close()
w = codecs.open(file_name, 'w', encoding='utf-8')
w.writelines(lines)
w.close()
这篇关于Python:UnicodeDecodeError:'ascii'编解码器无法解码位置0的字节0xef:序数不在范围内(128)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!