用python写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作
3 年前
import os
def alter_file(filename,old_value,new_value):
with open(filename,encoding="utf-8") as f, open("%s.bak"%filename,"w",encoding="utf-8") as f2:
# f.write("尹石榴,男\n")
# f.write("尹艺霏,女\t")
# new_value = "小"
# old_value = "尹"
for line in f:
if old_value in line:
line = line.replace(old_value,new_value)
f2.write(line)#写入
print("把%s替换成%s"%(old_value,new_value))
else:
print("这个%s不在文件中"%old_value)