Python 3.x 如何逐行更新文件中的文本

Python 3.x 如何逐行更新文件中的文本,python-3.x,file,search,replace,Python 3.x,File,Search,Replace,我有一个文本文件foo.txt,看起来像: first 01 start some thing 01 and more 101 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.c

我有一个文本文件foo.txt,看起来像:

first 01
start
some thing 01  
and more 101  
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)
我想将同一foo.txt中startend行之间的所有01替换为10,如下所示:

first 01
start
some thing 10
and more 110
i dont care
end
i dont care
final 01
到目前为止,我的代码如下所示:

first 01
start
some thing 01  
and more 101  
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)
它做了我想要的,但是我想知道是否有其他有效的方法来编写代码。我来自嵌入式背景,所以我在代码中使用了search等标志


谢谢

我不太确定您希望逐行读取和写入文件的用例,但与您的方法不同,我只是将文件读入一个字符串变量,然后将所有出现的“01”替换为“10”。你的代码看起来像这样

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

seek(0)函数将文件偏移量设置为文件的开头。因此,从这一点开始写入将覆盖整个文件

我不太确定您希望逐行读取和写入文件的用例,但与您的方法不同,我只是将文件读入一个字符串变量,然后将所有出现的“01”替换为“10”。你的代码看起来像这样

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

seek(0)函数将文件偏移量设置为文件的开头。因此,从这一点开始写入将覆盖整个文件

谢谢你的建议。但是我不想替换整个文件,我只想替换开始和结束之间的行谢谢你的建议。但是我不想替换整个文件,我只想替换开始和结束之间的行