最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python文件特定行插入和替換實(shí)例詳解

 更新時(shí)間:2017年07月12日 08:44:49   作者:ryanstd  
這篇文章主要介紹了python文件特定行插入和替換實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下

python文件特定行插入和替換實(shí)例詳解

python提供了read,write,但和很多語言類似似乎沒有提供insert。當(dāng)然真要提供的話,肯定是可以實(shí)現(xiàn)的,但可能引入insert會(huì)帶來很多其他問題,比如在插入過程中crash掉可能會(huì)導(dǎo)致后面的內(nèi)容沒來得及寫回。

不過用fileinput可以簡(jiǎn)單實(shí)現(xiàn)在特定行插入的需求:

Python代碼 

import os 
import fileinput 
def file_insert(fname,linenos=[],strings=[]): 
  """ 
  Insert several strings to lines with linenos repectively. 
 
  The elements in linenos must be in increasing order and len(strings) 
  must be equal to or less than len(linenos). 
 
  The extra lines ( if len(linenos)> len(strings)) will be inserted 
  with blank line. 
  """ 
  if os.path.exists(fname): 
    lineno = 0 
    i = 0 
    for line in fileinput.input(fname,inplace=1): 
      # inplace must be set to 1 
      # it will redirect stdout to the input file 
      lineno += 1 
      line = line.strip() 
      if i<len(linenos) and linenos[i]==lineno: 
        if i>=len(strings): 
          print "\n",line 
        else: 
          print strings[i] 
          print line 
        i += 1 
      else: 
        print line 
file_insert('a.txt',[1,4,5],['insert1','insert4']) 

 其中需要注意的是 fileinput.input的inplace必須要設(shè)為1,以便讓stdout被重定向到輸入文件里。

當(dāng)然用fileinput.input可以不僅用來在某行插入,還可以在特定模式的行(比如以salary:結(jié)尾的行)插入或替換,實(shí)現(xiàn)一個(gè)小型的sed。

以上就是python文件特定行插入和替換的簡(jiǎn)單實(shí)例,如果大家有不明白或者好的建議請(qǐng)到留言區(qū)或者社區(qū)提問和交流,使用感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論

汝州市| 三明市| 称多县| 定日县| 佛山市| 吉首市| 江西省| 平邑县| 卫辉市| 霍州市| 绿春县| 钟山县| 上高县| 法库县| 巫山县| 屯留县| 若尔盖县| 沙洋县| 黄骅市| 衡南县| 梨树县| 万盛区| 铜陵市| 辽宁省| 泰宁县| 南澳县| 靖远县| 北安市| 樟树市| 韶关市| 曲靖市| 甘德县| 巫山县| 高密市| 平邑县| 平阳县| 泰和县| 汉沽区| 贵德县| 郴州市| 孟州市|