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

时间:2017-03-03 20:47:00

标签: python-3.x file find edit

我有一个文本文件 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)

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

1 个答案:

答案 0 :(得分:1)

您的代码似乎缺少某些内容(例如DF_Generated = structure(list(PO_ID = c("P1234", "P1234", "P1234", "P1234", "P1234", "P1234", "P2345", "P2345", "P3456", "P4567"), SO_ID = c("S1", "S1", "S2", "S2", "S2", "S2", "S3", "S3", "S7", "S10"), F_Year = c(2012, 2012, 2013, 2013, 2013, 2013, 2011, 2011, 2014, 2015), Product_ID = c("385X", "385X", "450X", "450X", "450X", "900X", "3700", "3700", "A11U", "2700"), Location1 = c("MA", "NY", "WA", "NY", "WA", "NY", "IL", "IL", "MN", "CA"), Revenue = c(25, 25, 23.3333333333333, 23.3333333333333, 23.3333333333333, 35, 50, 50, 50, 100), Quantity = c(1.5, 1.5, 6.66666666666667, 6.66666666666667, 6.66666666666667, 20, 10, 10, 20, 40)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L), .Names = c("PO_ID", "SO_ID", "F_Year", "Product_ID", "Location1", "Revenue", "Quantity")) 是一个字符串而没有searchPattern属性),但您可以使用search来获取下一行代码找到搜索模式时文件迭代器。

改编自您的代码:

next()