2017-03-03 46 views
1

在一個文件中的行文本我有一個文本文件foo.txt的,看起來像:如何更新一行

first 01 
start 
some thing 01 
and more 101 
i dont care 
end 
i dont care 
final 01 

我想與全部更換線路之間啓動在同一foo.txt的,像這樣:

first 01 
start 
some thing 10 
and more 110 
i dont care 
end 
i dont care 
final 01 

我到目前爲止的代碼看起來像:

import re 
from tempfile import mkstemp 
from shutil import move 
from os import remove, close 
def replace(foo.txt): 
    searchStart = re.compile("^start") 
    searchEnd = re.compile("^end") 
    pattern = "01" 
    subst = "10" 
    fh, abs_path = mkstemp() 
    search = 0 
    with open(abs_path,'w') as new_file: 
     with open(file_path) as old_file: 
      for line in old_file: 
       if searchEnd.search(line): 
        search = 0 
       elif searchStart.search(line): 
        search = 1 
       if search == 1: 
        new_file.write(re.sub(pattern,subst,line)) 
       else: 
        new_file.write(line) 
    close(fh) 
    remove(foo.txt) 
    move(abs_path, foo.txt) 

它做我想要什麼,但我想知道是否有寫代碼的任何其他有效的方法。我來自嵌入式背景,所以我正在使用標誌在我的代碼中搜索

謝謝!

回答

0

我不太清楚你的用例是想要逐行讀寫文件,而不是你的方法,我只是簡單地將文件讀入字符串變量,然後將所有出現的'01 '與'10'。你的代碼看起來像這樣。

with open('testPy.txt', "r+") as f: 
    data = f.read().replace('01', '10') 
    f.seek(0) 
    f.write(data) 

seek(0)函數將文件偏移設置爲文件的開頭。因此,從這一點開始編寫將覆蓋整個文件。

+0

感謝您的建議。但我不想替換整個文件,我想只在開始和結束之間替換該行 –