|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
各位大佬,小弟在做一个任务的课后题,然后代码只有第一次可以正确运行,但是后面都报编码的错,请各位大佬指点迷津,程序如下:
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
>>>
|
|