搜索文本文件并插入行

时间:2013-02-28 23:41:26

标签: python file-io

我想要做的是(使用下面的文本作为示例),在文本文件中搜索字符串“Text2”,然后在“Text 2”之后插入一行(“Inserted Text”)两行。 “文本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,

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

3 个答案:

答案 0 :(得分:2)

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

searchline = 'Text4'
lines = f.readlines() # f being the file handle
i = lines.index(searchline) # Make sure searchline is actually in the file

现在i包含行Text4的索引。你可以使用它和list.insert(i,x)之前插入:

lines.insert(i, 'Random text to insert')

或之后:

lines.insert(i+1, 'Different random text')

或之后的三行:

lines.insert(i+3, 'Last example text')

只需确保包含IndexError的错误处理,您就可以随意使用。

答案 1 :(得分:2)

您可以使用

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)

答案 2 :(得分:2)

快速肮脏的方式就是那样

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,
相关问题