练习题1:
python your_script.py old_str new_str filename
对指定文件内容进行全局替换,替换完成后打印替换了多少处内容
#!/usr/bin/env python # -*- coding: utf-8 -*-
import sys
import os
cmd = [i for i in sys.argv]
old_str = cmd[1]
new_str = cmd[2]
file_name = cmd[3]
new_file = cmd[3]+"new"
f = open(file_name,"r")
f_tmp = open(new_file,"w")
count = 0
for line in f:
if old_str in line:
count += line.count(old_str)
line = line.replace(old_str, new_str)
f_tmp.write(line)
else:
f_tmp.write(line)
f.close()
f_tmp.close()
os.replace(new_file,file_name)
print("replace %d times" % count)