国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現替換文件中指定內容的方法

2020-01-04 15:37:08
字體:
來源:轉載
供稿:網友

本文實例講述了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教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 上思县| 宁都县| 南安市| 霍山县| 巴彦县| 会宁县| 海南省| 商城县| 延庆县| 永川市| 肥城市| 赤水市| 宁都县| 灵山县| 本溪| 乌兰浩特市| 乌兰浩特市| 永城市| 民勤县| 灵璧县| 柳林县| 河东区| 临沧市| 桐梓县| 手机| 辽宁省| 萨迦县| 长阳| 旬阳县| 象山县| 保德县| 抚松县| 灌云县| 雅安市| 荆州市| 邯郸县| 晴隆县| 永吉县| 临沧市| 沙坪坝区| 景东|