實現簡單sed替換功能的python腳本

#能夠用來修改配置文件參數spa

 

 1 # -*- coding:utf-8 -*-
 2 import os,sys
 3 old = sys.argv[1]
 4 new = sys.argv[2]
 5 file = sys.argv[3]
 6 file2 = sys.argv[3]
 7 tmp_file ="tmpfile"
 8 f = open(file,"r")
 9 f2 = open(tmp_file,"r+")
10 for line in f:
11     if old in line:
12         line= str.replace(line,old,new)
13         f2.write(line)
14     f2.write(line)
15     f2.flush()
16 f.close()
17 f2.close()
18 
19 os.remove(file)
20 os.rename(tmp_file,file2)



 好用的sedcode

 1 def sed_file(file_name,old,new):
 2     f = open(file_name)
 3     f2 = open("%s.bak"%file_name,"a+")
 4     for line in f:
 5         if line.startswith(old):
 6             line = str.replace(line,old,new)
 7             f2.write(line)
 8             f2.flush()
 9             continue
10         f2.write(line)
11         f2.flush()
12 
13     f.close()
14     f2.close()
15 
16     os.remove(file_name)
17     os.rename("%s.bak"%file_name,file_name)
相關文章
相關標籤/搜索