Python第29讲“全部替换”代码问题
第29讲中的全部替换问题,为什么下面代码不对,说是io.UnsupportedOperation: not readable,为什么def file_replace(file_name,oldword,newword):
f_read = open(str(file_name),encoding='utf-8')
count = 0
for each_line in f_read:
if oldword in each_line:
count = count+each_line.count(oldword)
f_read.close()
choose = input('\n文件%s中共有%d个【%s】\n是否将将【%s】全部替换为【%s】?\n 【YES/NO】:' % (file_name,count,oldword,oldword,newword))
if choose in ['YES','yes','Yes']:
f_write = open(str(file_name),'w',encoding='utf-8')
for each_line in f_write:
if oldword in each_line:
each_line.replace(oldword,newword)
f_write.close()
file_name = input('请输入文件名:')
oldword = input('请输入需要替换的单词或字符:')
newword = input('请输入新的单词或字符:')
file_replace(file_name, oldword, newword)
f_read = open(str(file_name), ‘r’, encoding='utf-8')
可能是这样的 本帖最后由 Twilight6 于 2020-6-7 21:42 编辑
for each_line in f_write:
if oldword in each_line:
each_line.replace(oldword,newword)
你打开是写入打开,不能遍历,你用 writeline 写入可迭代对象就好了:
正确代码:
def file_replace(file_name,oldword,newword):
f_read = open(str(file_name),encoding='utf-8')
count = 0
content = []
for each_line in f_read:
if oldword in each_line:
content.append(each_line.replace(oldword, newword))
count = count+each_line.count(oldword)
f_read.close()
choose = input('\n文件%s中共有%d个【%s】\n是否将将【%s】全部替换为【%s】?\n 【YES/NO】:' % (file_name,count,oldword,oldword,newword))
if choose in ['YES','yes','Yes']:
f_write = open(file_name,'w',encoding='utf-8')
f_write.writelines(content)
f_write.close()
file_name = input('请输入文件名:')
oldword = input('请输入需要替换的单词或字符:')
newword = input('请输入新的单词或字符:')
file_replace(file_name, oldword, newword)
7。8段貌似有点问题吧。。。。。。。
页:
[1]