99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python實(shí)現(xiàn)修改文件內(nèi)容的方法分析
Python實(shí)現(xiàn)修改文件內(nèi)容的方法分析
2018-06-06
收藏

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

本文實(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í)文件來存儲(chǔ)數(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()返回一個(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)

方法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  #會(huì)生成備份文件zhai.confbak

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

① os.system(command)

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

② os.popen(command,mode)

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

③ commands.getstatusoutput(command)

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

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

⑤ subprocess.Popen(command, shell=True)

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

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

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

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

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

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }