python文件特定行插入和替換實例詳解
python文件特定行插入和替換實例詳解
python提供了read,write,但和很多語言類似似乎沒有提供insert。當(dāng)然真要提供的話,肯定是可以實現(xiàn)的,但可能引入insert會帶來很多其他問題,比如在插入過程中crash掉可能會導(dǎo)致后面的內(nèi)容沒來得及寫回。
不過用fileinput可以簡單實現(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é)尾的行)插入或替換,實現(xiàn)一個小型的sed。
以上就是python文件特定行插入和替換的簡單實例,如果大家有不明白或者好的建議請到留言區(qū)或者社區(qū)提問和交流,使用感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
numpy庫與pandas庫axis=0,axis= 1軸的用法詳解
這篇文章主要介紹了numpy庫與pandas庫axis=0,axis= 1軸的用法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05pytorch模型預(yù)測結(jié)果與ndarray互轉(zhuǎn)方式
今天小編就為大家分享一篇pytorch模型預(yù)測結(jié)果與ndarray互轉(zhuǎn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01anaconda安裝pytorch1.7.1和torchvision0.8.2的方法(親測可用)
這篇文章主要介紹了anaconda安裝pytorch1.7.1和torchvision0.8.2的方法(親測可用),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02