contact_list.txt fileinputreadfile.py scan1.py test.py
csvt01 manage_query.py scanhostport.py test.txt
csvtpy newtext.txt tab.py userinput.py
fileinputbak.py oldtext.txt
root@kali:~/python# cat contact_list.txt
tom it m 18912378667 shanghai
jack op m 15876544332 beijin
lilei it m 15325635588 taiwan
flake it w 18900378667 nanchang
alex op m 15833544332 shijiazang
lili lp m 15123635588 hangzhou
mayun xi m 18912345667 ningbo
zhang py w 15876541222 yunnan
lisi op m 15333333333 haikou
wangwu java m 18999999999 shandong
song js w 15000000000 shenzhen
caiqi js w 15555555555 huizhou
root@kali:~/python# vim fileinputbak.py
root@kali:~/python# cat fileinputbak.py
#!/usr/bin/python
import fileinput
for line in fileinput.input('contact_list.txt',backup='.bak',inplace=1): //把contact_list.txt'原文件进行一份备份后,并对源文件进行修改,inplace=1表示进行修改
line = line.replace('tom','thomas') //对源文件中tom值替换成thomas值
print line
root@kali:~/python# ls
contact_list.txt fileinputreadfile.py scan1.py test.py
csvt01 manage_query.py scanhostport.py test.txt
csvtpy newtext.txt tab.py userinput.py
fileinputbak.py oldtext.txt tab.pyc xwbtest.txt
root@kali:~/python# python fileinputbak.py
root@kali:~/python# ls
contact_list.txt fileinputbak.py oldtext.txt tab.pyc xwbtest.txt
contact_list.txt.bak fileinputreadfile.py scan1.py test.py
csvt01 manage_query.py scanhostport.py test.txt
csvtpy newtext.txt
root@kali:~/python# cat fileinputbak.py
#!/usr/bin/python
import fileinput
for line in fileinput.input('contact_list.txt',backup='.bak',inplace=1):
line = line.replace('tom','thomas')
print line
root@kali:~/python# cat contact_list.txt.bak //源文件完整性进行了备份
tom it m 18912378667 shanghai
jack op m 15876544332 beijin
lilei it m 15325635588 taiwan
flake it w 18900378667 nanchang
alex op m 15833544332 shijiazang
lili lp m 15123635588 hangzhou
mayun xi m 18912345667 ningbo
zhang py w 15876541222 yunnan
lisi op m 15333333333 haikou
wangwu java m 18999999999 shandong
song js w 15000000000 shenzhen
caiqi js w 15555555555 huizhou
root@kali:~/python# cat contact_list.txt
thomas it m 18912378667 shanghai //对源文件的tom替换成了thomas
jack op m 15876544332 beijin
lilei it m 15325635588 taiwan
flake it w 18900378667 nanchang
alex op m 15833544332 shijiazang
lili lp m 15123635588 hangzhou
mayun xi m 18912345667 ningbo
zhang py w 15876541222 yunnan
lisi op m 15333333333 haikou
wangwu java m 18999999999 shandong
song js w 15000000000 shenzhen
caiqi js w 15555555555 huizhou
root@kali:~/python#