[英]Search text file and insert line
我想要做的是(使用下面的文本作为示例),在文本文件中搜索字符串“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,
但我只是不知道如何在我正在文件中搜索的文本后添加两行。
快速肮脏的方式就是这样的
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,
如果将文件内容加载到列表中,则操作起来会更容易:
searchline = 'Text4'
lines = f.readlines() # f being the file handle
i = lines.index(searchline) # Make sure searchline is actually in the file
现在i
包含Text4
行的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
的错误处理,您就可以随意使用它。
你可以用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.