搜索文本文件并插入行

3 投票
3 回答
11734 浏览
提问于 2025-04-17 17:30

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

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)
3

一个简单粗暴的方法可以是这样的

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,
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错误,你就可以随心所欲地操作了。

撰写回答