Linux下Python 文件内容替换脚本

Linux下Python 文件替换脚本

import sys,os

if len(sys.argv)<=4:
    old_text,new_text = sys.argv[1],sys.argv[2]

file_name = sys.argv[3]

f = open(file_name,"rb")

new_file = open(".%s.bak" % file_name,"wb")

for line in f.xreadlines():
    print("usage:./file_replace.py old_text new_text filename")
    new_file.write(line.replace(old_text,new_text))
f.close()
new_file.close()

if "--bak"  in sys.argv:
    os.rename(file_name,".%s.bak2"%file_name)
    os.rename(".%s.bak"%file_name,file_name)
    os.rename("%s.bak2"%file_name,".%s.bak"%file_name)
else:
    os.rename(".%s.bak"%file_name,file_name)

 

posted @ 2016-12-15 22:17  Chaz_Sun  阅读(2006)  评论(0编辑  收藏  举报