国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python文件特定行插入和替換實例詳解

2020-02-16 01:50:32
字體:
來源:轉載
供稿:網友

python文件特定行插入和替換實例詳解

python提供了read,write,但和很多語言類似似乎沒有提供insert。當然真要提供的話,肯定是可以實現的,但可能引入insert會帶來很多其他問題,比如在插入過程中crash掉可能會導致后面的內容沒來得及寫回。

不過用fileinput可以簡單實現在特定行插入的需求:

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必須要設為1,以便讓stdout被重定向到輸入文件里。

當然用fileinput.input可以不僅用來在某行插入,還可以在特定模式的行(比如以salary:結尾的行)插入或替換,實現一個小型的sed。

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 郑州市| 开阳县| 崇阳县| 蒲城县| 宕昌县| 太和县| 镇巴县| 时尚| 敦化市| 独山县| 大连市| 项城市| 万全县| 香河县| 佛坪县| 松桃| 舒城县| 太仆寺旗| 民和| 洞口县| 同仁县| 闵行区| 纳雍县| 苏尼特左旗| 故城县| 宜良县| 清徐县| 教育| 大同市| 时尚| 巴青县| 平武县| 丹棱县| 五大连池市| 错那县| 延津县| 金坛市| 汉寿县| 平顶山市| 祁阳县| 阳信县|