2017-03-03 32 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

感谢您的建议。但我不想替换整个文件,我想只在开始和结束之间替换该行 –