Python實(shí)現(xiàn)替換文件中指定內(nèi)容的方法
本文實(shí)例講述了Python實(shí)現(xiàn)替換文件中指定內(nèi)容的方法。分享給大家供大家參考,具體如下:
這里使用python編寫(xiě)的程序,實(shí)現(xiàn)如下功能:將文件中的指定子串 修改為 另外的子串
編寫(xiě)的python程序,文件名是file_replace.py,具體代碼如下:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import sys,os
if len(sys.argv)<4 or len(sys.argv)>5:
sys.exit('There needs four or five parameters')
elif len(sys.argv)==4:
print 'usage:./file_replace.py old_text new_text filename'
else:
print 'usage:./file_replace.py old_text new_text filename --bak'
old_text,new_text=sys.argv[1],sys.argv[2]
file_name=sys.argv[3]
f=file(file_name,'rb')
new_file=file('.%s.bak' % file_name,'wb')#文件名以.開(kāi)頭的文件是隱藏文件
for line in f.xreadlines():#f.xreadlines()返回一個(gè)文件迭代器,每次只從文件(硬盤(pán))中讀一行
new_file.write(line.replace(old_text,new_text))
f.close()
new_file.close()
if '--bak' in sys.argv: #'--bak'表示要求對(duì)原文件備份
os.rename(file_name,'%s.bak' % file_name) #unchanged
os.rename('.%s.bak' % file_name,file_name) #changed
else:
os.rename(file_name,'wahaha.txt')#此處也可以將原文件刪除,以便下一語(yǔ)句能夠正常執(zhí)行
os.rename('.%s.bak' % file_name,file_name)
下面是代碼執(zhí)行的一個(gè)例子:
song@ubuntu:~$ more hello.txt Hello python Hello world python Hello world Hello song@ubuntu:~$ python file_replace.py Hello love hello.txt --bak usage:./file_replace.py old_text new_text filename --bak song@ubuntu:~$ ls Desktop Documents file_replace.py Music systemExit.py diff1.txt Downloads hello.txt Pictures Templates diff.txt examples.desktop hello.txt.bak Public Videos song@ubuntu:~$ more hello.txt love python love world python love world love song@ubuntu:~$ more hello.txt.bak Hello python Hello world python Hello world Hello song@ubuntu:~$
更多Python相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python入門(mén)與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
django和vue實(shí)現(xiàn)數(shù)據(jù)交互的方法
今天小編就為大家分享一篇django和vue實(shí)現(xiàn)數(shù)據(jù)交互的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08
將python運(yùn)行結(jié)果保存至本地文件中的示例講解
今天小編就為大家分享一篇將python運(yùn)行結(jié)果保存至本地文件中的示例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
如何解決flask修改靜態(tài)資源后緩存文件不能及時(shí)更改問(wèn)題
在本篇內(nèi)容里小編給大家整理的是關(guān)于如何解決flask修改靜態(tài)資源后緩存文件不能及時(shí)更改問(wèn)題,需要的朋友們可以學(xué)習(xí)下。2020-08-08
用python畫(huà)個(gè)奧運(yùn)五環(huán)(附完整代碼)
大家好,本篇文章主要講的是用python畫(huà)個(gè)奧運(yùn)五環(huán)(附完整代碼),感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話(huà)記得收藏一下2022-01-01

