熱線電話:13121318867

登錄
首頁精彩閱讀Python實現修改文件內容的方法分析
Python實現修改文件內容的方法分析
2018-06-06
收藏

Python實現修改文件內容的方法分析

本文實例講述了Python實現修改文件內容的方法。分享給大家供大家參考,具體如下:
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 臨時文件來存儲數據

實現如下功能:將文件中的指定子串 修改為 另外的子串

python 字符串替換可以用2種方法實現:

①是用字符串本身的方法。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')#此處也可以將原文件刪除,以便下一語句能夠正常執行
  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調用shell的方法

① os.system(command)

在一個子shell中運行command命令,并返回command命令執行完畢后的退出狀態。這實際上是使用C標準庫函數system()實現的。這個函數在執行command命令時需要重新打開一個終端,并且無法保存command命令的執行結果。

② os.popen(command,mode)

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

③ commands.getstatusoutput(command)

使用os. getstatusoutput ()函數執行command命令并返回一個元組(status,output),分別表示command命令執行的返回狀態和執行結果。對command的執行實際上是按照{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不是一個可執行文件,shell=True不可省。

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

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

將調用shell的結果賦值給python變量

代碼如下:    
handle = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
print handle.communicate()[0]

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢