python检索字符串后内容_在Python中查找字符串并在其后插入文本

这里有一个处理文件的建议,我认为您搜索的模式是一整行(没有什么比模式更适合一行)。line = ... # What to match

input_filepath = ... # input full path

output_filepath = ... # output full path (must be different than input)

with open(input_filepath, "r", encoding=encoding) as fin \

open(output_filepath, "w", encoding=encoding) as fout:

pattern_found = False

for theline in fin:

# Write input to output unmodified

fout.write(theline)

# if you want to get rid of spaces

theline = theline.strip()

# Find the matching pattern

if pattern_found is False and theline == line:

# Insert extra data in output file

fout.write(all_data_to_insert)

pattern_found = True

# Final check

if pattern_found is False:

raise RuntimeError("No data was inserted because line was not found")

这段代码是针对Python 3的,Python 2可能需要进行一些修改,特别是with语句(请参见contextlib.nested)。如果模式适合一行,但不是整行,则可以使用"theline in line",而不是"theline == line"。如果你的模式可以在多条线上传播,你需要一个更强的算法。:)

要写入同一个文件,可以写入另一个文件,然后将输出文件移到输入文件上。我不打算发布这段代码,但几天前我也遇到了同样的情况。所以这里有一个类,它在两个标记之间的文件中插入内容,并支持在输入文件中写入:https://gist.github.com/Cilyan/8053594

你可能感兴趣的:(python检索字符串后内容)