Python 搜索文本文件并插入行

Python 搜索文本文件并插入行,python,file-io,Python,File Io,我想做的是(以下面的文本为例),在文本文件中搜索字符串“Text2”,然后在“Text2”之后插入一行(“插入的文本”)。“文本2”可以在文本文件中的任何一行,但我知道它将在文本文件中出现一次 这是原始文件: Text1 Text2 Text3 Text4 这就是我想要的: Text1 Text2 Text3 Inserted Text Text 4 因此,我已经知道如何使用下面的代码在一行上方添加文本 for line in fileinput.input('file.txt', inpl

我想做的是(以下面的文本为例),在文本文件中搜索字符串“Text2”,然后在“Text2”之后插入一行(“插入的文本”)。“文本2”可以在文本文件中的任何一行,但我知道它将在文本文件中出现一次

这是原始文件:

Text1
Text2
Text3
Text4
这就是我想要的:

Text1
Text2
Text3
Inserted Text
Text 4
因此,我已经知道如何使用下面的代码在一行上方添加文本

for line in fileinput.input('file.txt', inplace=1,backup='.bak'):
    if line.startswith('Text 4'):
        print "Inserted Text"
        print line,
    else:
        print line,

但我不知道如何在文件中搜索的文本后两行添加内容。

如果将文件内容加载到列表中,操作起来会更容易:

searchline = 'Text4'
lines = f.readlines() # f being the file handle
i = lines.index(searchline) # Make sure searchline is actually in the file
现在
i
包含行
Text4
的索引。您可以使用它和
列表。插入(i,x)
以在以下内容之前插入:

lines.insert(i, 'Random text to insert')
或之后:

lines.insert(i+1, 'Different random text')
或三行之后:

lines.insert(i+3, 'Last example text')
只需确保为
索引器
s包含错误处理,您可以随意使用它。

您可以使用

f = open("file.txt","rw")
lines = f.readlines()
for i in range(len(lines)):
     if lines[i].startswith("Text2"):
            lines.insert(i+3,"Inserted text") #Before the line three lines after this, i.e. 2 lines later.

print "\n".join(lines)

快速肮脏的方式就是这样

before=-1
for line in fileinput.input('file.txt', inplace=1,backup='.bak'):
    if line.startswith('Text 2'):
        before = 2
    if before == 0
        print "Inserted Text"
    if before > -1
        before = before - 1
    print line,

print line和else子句是多余的,请在退出ifThis之后打印该行以获得精确匹配。对于以字符串开头的行或包含字符串的行,有什么类似的方法吗?我不知道有什么漂亮、简洁的方法可以做到这一点,尽管我的Python最近有些生疏。但据我所知,您必须迭代这些行以找到正确的索引,类似于@Boaan的解决方案。使用
如果第行中的“Text 2:
查找包含字符串的行如何将此字符串写入此文件?