搜尋此網誌

2013年3月17日 星期日

How to use python replace a word as sed does

import os,fileinput 
changing_file_dst='/Users/Hermes/Downloads/srt.txt' changefile=fileinput.input(changing_file_dst, inplace=1)
 # <==this is part very import if you just fileinput.input(change_file_dst) data will not modified , so you need set inplace=1 to modify current file 
for st in changefile:
 replace_str='cluster.enabled=true'
 pattern='cluster.enabled=false'
 result=st.replace(pattern,replace_str)
 print(result) changefile.close()

 original I just want use open , but when I write all file will be truncate and write . so I use fileinput.
原本是用open 將檔案 打開修改可是用 W mode 會因為先作truncated , 再寫入所以檔案會被清空 ,所以改用 fileinput 直接作修改

沒有留言: