|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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)
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)
count = eachline.count(rep_word) 为什么 这里是 = 不是 +=
还有 for eachline in f_read:
这个是逐行 读取??
if decide in ['YES', 'Yes', 'yes']:
f_write = open(file_name, 'w')
f_write.writelines(content)
f_write.close()
还有这段代码 为什么是 能把原来位置的 代码 替换成新的代码??
1. 我个人觉得应该是count += eachline.count(rep_word) ,否则无法叠加。
可参考这个帖子: http://bbs.fishc.com/forum.php?m ... B%B2%BF%CC%E6%BB%BB
2.for eachline in f_read: 这道题我也问过,感觉文件搭配for语句默认是按行来读取的,自己做做实验就知道了。至于为什么,等以后我能读懂python的语句如何实现,应该就能理解了。目前我只是默默记下来了。
3. if decide in ['YES', 'Yes', 'yes']:
f_write = open(file_name, 'w')
f_write.writelines(content)
f_write.close()
这是因为前面新建了一个content[]的空列表,在读取f_read的每行数据时,其实就已经把需要替换的内容全部放到content里面了。一旦决定替换,就可以将content的内容以覆盖源文件的方式写入。
|
|