找到一个模式并编辑下一行并使用 python 写回同一文件

find a pattern and edit the next line and write back to the same file using python

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

I dont care!
pattern and stuff
this line : to_edit
this line : no_edit
some other lines
this line : to_edit
pattern and stuff
another line : to_edit
another line : to_edit

我想找到模式并编辑仅下一行并且没有其他行并像这样写回相同的 foo.txt

I dont care!
pattern and stuff
this line : EDITED
this line : no_edit
some other lines
this line : to_edit
pattern and stuff
another line : EDITED
another line : to_edit

我也不想使用 f.readline() 和 f.seek() 我目前拥有的代码如下所示:

import re
from tempfile import mkstemp
from shutil import move
from os import remove, close
def replace(foo.txt):
    searchPattern = re.compile("^pattern")
    pattern = "to_edit"
    subst = "EDITED"
    fh, abs_path = mkstemp()
    nextLine = 0
    with open(abs_path,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                if nextLine == 0:
                    if searchPattern.search(line):
                        nextLine = 1
                        continue
                    else:
                        new_file.write(line)
                else:
                    new_file.write(re.sub(pattern,subst,line))
                    nextLine = 0
    close(fh)
    remove(foo.txt)
    move(abs_path, foo.txt)

我认为这是一种非常低效的编码和获取解决方案的方式。

您的代码似乎缺少一些东西(例如 searchPattern 是一个字符串并且没有 search 属性),但是您可以使用 next() 来获取下一行当您找到搜索模式时从文件迭代器中获取。

根据您的代码改编:

def replace(foo.txt):
    searchPattern = re.compile("^pattern")
    pattern = "to_edit"
    subst = "EDITED"
    fh, abs_path = mkstemp()
    with open(abs_path,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                # As it is, this next line should not work, but assuming that it returns True when the pattern is found..
                if searchPattern.search(line):
                    # Write current line
                    new_file.write(line)
                    # Get next line
                    next_line = next(old_file)
                    # Write edited line 
                    new_file.write(re.sub(pattern,subst,next_line))
                else:
                    new_file.write(line)