python替換檔案中的指定內容

2021-07-15 01:34:53 字數 1892 閱讀 8255

編寫的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()返回乙個檔案迭代器,每次只從檔案(硬碟)中讀一行

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) #changed

else:

os.rename(file_name,'wahaha.txt')#此處也可以將原檔案刪除,以便下一語句能夠正常執行

os.rename('.%s.bak' % file_name,file_name)

下面是**執行的乙個例子:

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修改替換檔案每行的指定字元

簡單的修改檔案裡的字串 有個朋友經常要修改一大堆檔案裡指定字元的批量修改 所以寫了下面一段 filename modified.txt hand str input 字首詞 strip endwith str input 字尾詞 strip change str input 要修改的整數初始值 fi...

python批量替換資料夾內的檔案內容

author jingyuan import os import re 要改的資料夾 dir e testscript 要改的檔案型別 可以輸入多個 file type htm 替換表 可以用python正規表示式 look up table map list a c a b def get fil...

python批量替換檔案內的字串

coding utf 8 import os import io def alter file,old str,new str 替換檔案中的字串 param file 檔名 param old str 就字串 param new str 新字串 return file data with io.op...