实现简单sed替换功能的python脚本

时间:2024-08-03 16:36:14

#可以用来修改配置文件参数

 # -*- coding:utf-8 -*-
import os,sys
old = sys.argv[1]
new = sys.argv[2]
file = sys.argv[3]
file2 = sys.argv[3]
tmp_file ="tmpfile"
f = open(file,"r")
f2 = open(tmp_file,"r+")
for line in f:
if old in line:
line= str.replace(line,old,new)
f2.write(line)
f2.write(line)
f2.flush()
f.close()
f2.close() os.remove(file)
os.rename(tmp_file,file2)

好用的sed

 def sed_file(file_name,old,new):
f = open(file_name)
f2 = open("%s.bak"%file_name,"a+")
for line in f:
if line.startswith(old):
line = str.replace(line,old,new)
f2.write(line)
f2.flush()
continue
f2.write(line)
f2.flush() f.close()
f2.close() os.remove(file_name)
os.rename("%s.bak"%file_name,file_name)