溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python實(shí)現(xiàn)修改文件內(nèi)容的方法分析

發(fā)布時間:2020-09-05 19:12:56 來源:腳本之家 閱讀:148 作者:翟海飛 欄目:開發(fā)技術(shù)

本文實(shí)例講述了Python實(shí)現(xiàn)修改文件內(nèi)容的方法。分享給大家供大家參考,具體如下:

1 替換文件中的一行

1.1 修改原文件

① 要把文件中的一行Server=192.168.22.22中的IP地址替換掉,因此把整行替換。

data = ''
with open('zhai.conf', 'r+') as f:
  for line in f.readlines():
    if(line.find('Server') == 0):
      line = 'Server=%s' % ('192.168.1.1',) + '\n'
    data += line
with open('zhai.conf', 'r+') as f:
  f.writelines(data)

② 把原文件的hello替換成world。

#!/usr/local/bin/python
#coding:gbk
import re
old_file='/tmp/test'
fopen=open(old_file,'r')
w_str=""
for line in fopen:
  if re.search('hello',line):
    line=re.sub('hello','world',line)
    w_str+=line
  else:
    w_str+=line
print w_str
wopen=open(old_file,'w')
wopen.write(w_str)
fopen.close()
wopen.close()

1.2 臨時文件來存儲數(shù)據(jù)

實(shí)現(xiàn)如下功能:將文件中的指定子串 修改為 另外的子串

python 字符串替換可以用2種方法實(shí)現(xiàn):

①是用字符串本身的方法。str.replace方法。
②用正則來替換字符串: re

方法1:

#!/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')#此處也可以將原文件刪除,以便下一語句能夠正常執(zhí)行
  os.rename('.%s.bak' % file_name,file_name)

方法2:

open('file2', 'w').write(re.sub(r'world', 'python', open('file1').read()))

2 使用sed

2.1 sed命令:

sed -i "/^Server/ c\Server=192.168.0.1" zhai.conf  #-i表示在原文修改
sed -ibak "/^Server/c\Server=192.168.0.1" zhai.conf  #會生成備份文件zhai.confbak

2.2 python調(diào)用shell的方法

os.system(command)

在一個子shell中運(yùn)行command命令,并返回command命令執(zhí)行完畢后的退出狀態(tài)。這實(shí)際上是使用C標(biāo)準(zhǔn)庫函數(shù)system()實(shí)現(xiàn)的。這個函數(shù)在執(zhí)行command命令時需要重新打開一個終端,并且無法保存command命令的執(zhí)行結(jié)果。

os.popen(command,mode)

打開一個與command進(jìn)程之間的管道。這個函數(shù)的返回值是一個文件對象,可以讀或者寫(由mode決定,mode默認(rèn)是'r')。如果mode為'r',可以使用此函數(shù)的返回值調(diào)用read()來獲取command命令的執(zhí)行結(jié)果。

commands.getstatusoutput(command)

使用os. getstatusoutput ()函數(shù)執(zhí)行command命令并返回一個元組(status,output),分別表示command命令執(zhí)行的返回狀態(tài)和執(zhí)行結(jié)果。對command的執(zhí)行實(shí)際上是按照{(diào)command;} 2>&1的方式,所以output中包含控制臺輸出信息或者錯誤信息。output中不包含尾部的換行符。

subprocess.call(["some_command","some_argument","another_argument_or_path"])
subprocess.call(command,shell=True)**

subprocess.Popen(command, shell=True)

如果command不是一個可執(zhí)行文件,shell=True不可省。

使用subprocess模塊可以創(chuàng)建新的進(jìn)程,可以與新建進(jìn)程的輸入/輸出/錯誤管道連通,并可以獲得新建進(jìn)程執(zhí)行的返回狀態(tài)。使用subprocess模塊的目的是替代os.system()、os.popen*()、commands.*等舊的函數(shù)或模塊。

最簡單的方法是使用class subprocess.Popen(command,shell=True)。Popen類有Popen.stdin,Popen.stdoutPopen.stderr三個有用的屬性,可以實(shí)現(xiàn)與子進(jìn)程的通信。

將調(diào)用shell的結(jié)果賦值給python變量

代碼如下:

handle = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
print handle.communicate()[0]

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》

希望本文所述對大家Python程序設(shè)計(jì)有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI