本帖最后由 kylin121380 于 2020-9-10 21:55 编辑
count=0不是xount=0, for eachline in f_read.read()是f_read.read()不是f_read, decide有五个%后面括号内只写了四个。def file_replace(file_name,rep_word, new_word):
f_read = open(file_name, encoding='utf-8')
content = [] # 修改后保存
count = 0
for eachline in f_read.read():
if rep_word in eachline:
count += eachline.count(rep_word) # 需替换词计数
eachline = eachline.replace(rep_word, new_word) # 替换
content.append(eachline) # 修改后保存
decide = input('\n文件 %s 中共有%s个【%s】\n你确定要把所有的【%s】替换为【%s】吗?\n【YES/NO】:'\
% (file_name, count, rep_word,rep_word, new_word))
if decide in ['YES', 'Yes', 'yes']:
f_write = open(file_name, 'w')
f_write.writelines(content) # 写入
f_write.close()
f_read.close()
file_name = input('请输入文件名:')
rep_word = input('请输入需要替换的单词或字符:')
new_word = input('请输入新的单词或字符:')
file_replace(file_name, rep_word, new_word)
|