搜索文本文件并插入行 [英] Search text file and insert line
问题描述
所以这是原始文件:
Text1
$
Text2
Text3
Text4
$ b这是我想要的:
Text1
Text2
Text3
插入文本
文本4
知道如何使用下面的代码添加一行上面的文本。
for file in fileinput.input('file.txt', inplace = 1,backup ='。bak'):
如果line.startswith('Text 4'):
打印插入文本
打印行,
else:
print line,
但是我只是不知道如何在文本我在文件中搜索。
解决方案如果您将文件内容加载到列表中,操作:
searchline ='Text4'
lines = f.readlines()#f是文件句柄
i = lines.index(searchline)#确保searchline实际上在文件
现在
i
包含行文本4
。你可以使用list.insert(i,x)
来插入:
lines.insert(i,'随机插入的文本')
或之后:
lines.insert(i + 1,'Different random text')
pre>
或者三行之后:
$ $ $ $ $ $ $ $ $ line.insert(i +3,'Last example text')
只要确保包含<$ c $的错误处理c> IndexError s,你可以用它来做任何事情。
What I want to do is (using the text below as an example), search for the string "Text2" in a text file, and then insert a line ("Inserted Text") two lines after "Text 2". "Text 2" could be on any line in the text file but I know it will appear once within the text file.
So here’s the original file:
Text1 Text2 Text3 Text4
And here’s what I want:
Text1 Text2 Text3 Inserted Text Text 4
So I already know how to add text above a line using the code below.
for line in fileinput.input('file.txt', inplace=1,backup='.bak'): if line.startswith('Text 4'): print "Inserted Text" print line, else: print line,
But I just don't know how to add something two lines after the text I'm searching for in the file.
解决方案If you load the file contents into a list, it would be easier to manipulate:
searchline = 'Text4' lines = f.readlines() # f being the file handle i = lines.index(searchline) # Make sure searchline is actually in the file
Now
i
contains the index of the lineText4
. You can use that andlist.insert(i,x)
to insert before:lines.insert(i, 'Random text to insert')
Or after:
lines.insert(i+1, 'Different random text')
Or three lines after:
lines.insert(i+3, 'Last example text')
Just make sure to include error handling for
IndexError
s and you can do with that whatever you want.这篇关于搜索文本文件并插入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!