本文實例講述了Python實現替換文件中指定內容的方法。分享給大家供大家參考,具體如下:
這里使用python編寫的程序,實現如下功能:將文件中的指定子串 修改為 另外的子串
編寫的python程序,文件名是file_replace.py,具體代碼如下:
#!/usr/bin/env python#_*_ coding:utf-8 _*_import sys,osif 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')#文件名以.開頭的文件是隱藏文件for line in f.xreadlines():#f.xreadlines()返回一個文件迭代器,每次只從文件(硬盤)中讀一行 new_file.write(line.replace(old_text,new_text))f.close()new_file.close()if '--bak' in sys.argv: #'--bak'表示要求對原文件備份 os.rename(file_name,'%s.bak' % file_name) #unchanged os.rename('.%s.bak' % file_name,file_name) #changedelse: os.rename(file_name,'wahaha.txt')#此處也可以將原文件刪除,以便下一語句能夠正常執行 os.rename('.%s.bak' % file_name,file_name)下面是代碼執行的一個例子:
song@ubuntu:~$ more hello.txtHello pythonHello worldpython Helloworld Hellosong@ubuntu:~$ python file_replace.py Hello love hello.txt --bakusage:./file_replace.py old_text new_text filename --baksong@ubuntu:~$ lsDesktop Documents file_replace.py Music systemExit.pydiff1.txt Downloads hello.txt Pictures Templatesdiff.txt examples.desktop hello.txt.bak Public Videossong@ubuntu:~$ more hello.txtlove pythonlove worldpython loveworld lovesong@ubuntu:~$ more hello.txt.bakHello pythonHello worldpython Helloworld Hellosong@ubuntu:~$
更多Python相關內容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python編碼操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答