|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 huyanmin 于 2021-1-25 11:56 编辑
#对源程序,略改动,报错,找不到出错原因
def filereplace(filename,old_word,new_word):
with open(filename,encoding='utf-8') as file:
list =[]
count=0
for line in file:
for old_word in line:
count += line.count(old_word)
line = line.replace(old_word,new_word)
list.append(line)
file.close() #此处改动,源代码不在此位置,在最后面 ,改到此处有区别吗?
decide = input('\n文件%s中共有%d个【%s】\n您确定要把所有的【%s】替换为【%s】吗?\n\
【YES/NO】:)
if decide in ['YES','Yes','yes']:
with open(filename,'w',encoding='utf-8') as file:
file.writelines(list)
file.close()
filename = input('请输入文件名:')
old-word = input('请输入需要替换的单词或字符:')
new-word = input('请输入新的单词或字符:')
filereplace(filename,old-word,new-word)
#源代码
def file_replace(file_name, rep_word, new_word):
f_read = open(file_name)
content = []
count = 0
for eachline in f_read:
if rep_word in eachline:
count = eachline.count(rep_word) #count感觉应该用这个
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)
with是上下文管理,不需要手动close,还有,平时连续打开的流程都是打开->关闭->打开->关闭
|
|