编辑 Python 中的文件并将结果写入新文件,但仅限于特定区域

Edit a File in Python and write the results on a new file but only in specific areas

我想制作一个脚本来执行以下操作:

我 file_ori.txt 它的内容是这样的(数字只是行号而不是实际文本)

1 This is test line with random text
2 This is also a line with lalala text
3 This is that and this and that of a line
4 start sequence
5 This isn't also a line with lalala text
6 This is test line with random text
7 This is also a line with lalala text
8 end sequence
9 This is test line with random text

我想要帮助的是在整个文件中将单词 "line" 更改为单词 "Pine",但只传递新文件中 start sequence 和 [=15 之间的更改=] 结果是这样的:

1 This is test line with random text
2 This is also a line with lalala text
3 This is that and this and that of a line
4 start sequence
5 This isn't also a Pine with lalala text
6 This is test Pine with random text
7 This is also a Pine with lalala text
8 end sequence
9 This is test line with random text

在我的情况下,我不想在替换之前拆分文件,而只是在之后拆分文件,这一点至关重要。我必须努力阅读全文。

f = open(file_ori.txt, "r")
full_read = f.read()

full_read = full_read.replace('line', 'Pine')

............. I don't know how to continue

f = open(file_ori_edit.txt, 'w')
    f.write(full_read)
    f.close()

谢谢。

这是一种方法。

例如:

start = 'start sequence'
end = 'end sequence'
parse = False
result = []
with open(filename) as infile:
    for line in infile:      #Iterate each line
        line = line.strip()
        if start == line:    #check for start sequence
            parse = True
        if end == line:      #check for end sequence
            parse = False

        if parse:   #Replace ONLY between sequence
            line = line.replace('line', 'Pine')
        result.append(line+"\n")

with open(filename, "w") as outfile:
    outfile.writelines(result)