关于字符替换的问题
各位大佬,小弟在做一个任务的课后题,然后代码只有第一次可以正确运行,但是后面都报编码的错,请各位大佬指点迷津,程序如下:def replace(file_name,str_rep,str_new):
cap = []
count = 0
f_read = open(file_name,encoding = 'UTF-8')
for eachline in f_read:
if str_rep in eachline:
count += 1
eachline = eachline.replace(str_rep,str_new)
cap.append(eachline)
decide = input('是否替换/yes or no?')
if decide in ['yes','YES','Yes']:
f_write = open(file_name, 'w')
f_write.writelines(cap)
f_write.close()
f_read.close()
file_name = input('请输入文件名')
str_rep = input('请输入需要替换的字符:')
str_new = input('请输入需要新的字符:')
replace(file_name,str_rep,str_new)
执行程序后,只有第一次可行
========
请输入文件名222.txt
请输入需要替换的字符:一
请输入需要新的字符:二
是否替换/yes or no?yes
>>>
============ RESTART: C:/Users/Administrator/Desktop/py作业/一个任务/替换.py ===========
请输入文件名222.txt
请输入需要替换的字符:二
请输入需要新的字符:一
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/py作业/一个任务/替换.py", line 19, in <module>
replace(file_name,str_rep,str_new)
File "C:/Users/Administrator/Desktop/py作业/一个任务/替换.py", line 5, in replace
for eachline in f_read:
File "H:\Python\install\lib\codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte
>>>
============ RESTART: C:/Users/Administrator/Desktop/py作业/一个任务/替换.py ===========
请输入文件名222.txt
请输入需要替换的字符:二
请输入需要新的字符:一
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/py作业/一个任务/替换.py", line 19, in <module>
replace(file_name,str_rep,str_new)
File "C:/Users/Administrator/Desktop/py作业/一个任务/替换.py", line 5, in replace
for eachline in f_read:
File "H:\Python\install\lib\codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte
>>>
改成这样试试:
def replace(file_name,str_rep,str_new):
cap = []
count = 0
f_read = open(file_name,encoding = 'UTF-8')
for eachline in f_read:
if str_rep in eachline:
count += 1
eachline = eachline.replace(str_rep,str_new)
cap.append(eachline)
decide = input('是否替换/yes or no?')
if decide in ['yes','YES','Yes']:
f_write = open(file_name, 'w', encoding = 'UTF-8')
f_write.writelines(cap)
f_write.close()
f_read.close()
file_name = input('请输入文件名')
str_rep = input('请输入需要替换的字符:')
str_new = input('请输入需要新的字符:')
replace(file_name,str_rep,str_new) qiuyouzhi 发表于 2021-2-23 19:55
改成这样试试:
感谢回复!按照您说的试了一下还是不行,报以下错误
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte
我把f_read = open(file_name,encoding = 'UTF-8')这段代码改为f_read = open(file_name)又可以正常运行了
页:
[1]