搜索文本文件并插入行 [英] Search text file and insert line

查看:126
本文介绍了搜索文本文件并插入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是(使用下面的文本作为例子),在文本文件中搜索字符串Text2,然后在Text 2后面插入一行(插入文本)两行。 文本2可以在文本文件的任何一行,但我知道它会出现在文本文件中。



所以这是原始文件:

  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 line Text4. You can use that and list.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 IndexErrors and you can do with that whatever you want.

这篇关于搜索文本文件并插入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆