python替换文件内容_Python实现替换文件中指定内容的方法
本文實(shí)例講述了Python實(shí)現(xiàn)替換文件中指定內(nèi)容的方法。分享給大家供大家參考,具體如下:
這里使用python編寫的程序,實(shí)現(xiàn)如下功能:將文件中的指定子串 修改為 另外的子串
編寫的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')#文件名以.開頭的文件是隱藏文件
for line in f.xreadlines():#f.xreadlines()返回一個(gè)文件迭代器,每次只從文件(硬盤)中讀一行
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')#此處也可以將原文件刪除,以便下一語句能夠正常執(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)容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
本文標(biāo)題: Python實(shí)現(xiàn)替換文件中指定內(nèi)容的方法
本文地址: http://www.cppcns.com/jiaoben/python/222897.html
總結(jié)
以上是生活随笔為你收集整理的python替换文件内容_Python实现替换文件中指定内容的方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux中模拟延时与丢包的实现
- 下一篇: apache shiro版本查看_深入学