[英]Python read append more that one line to a list from a text file
我有一个网络设备配置的文本文件,并且我的脚本循环遍历文件的各行,这是我要查找的内容:
如果脚本在行中找到了特定的单词,我希望将脚本附加到列表中。 到目前为止,我只能在列表中添加一行...这是一个示例:
my_file = open('configs.txt', 'r')
license = []
for line in my_file:
if line.startswith ("show license verbose"):
license.append(line)
print license
到目前为止,我只得到一行带有“ show license verbose”的行。 我想让我在找到该词组后再说5行。
谢谢。
my_file = open('configs.txt', 'r')
license = []
for line in my_file:
if line.startswith ("show license verbose"):
license.append(line)
for (i, line) in zip( range(1, 6), my_file ):
license.append( line )
print( license )
这是python 2的python3代码,您可能希望删除最后打印的括号并使用xrange
而不是range
您可以使用itertools.islice
从文件对象中获取后续行:
from itertools import islice
my_file = open('configs.txt', 'r')
license = []
for line in my_file:
if line.startswith("show license verbose"):
license.append(line)
license.extend(islice(my_file, 5))
print license
open返回一个生成器,因此您可以使用下一个方法:
# you don't need this input as you already has generator
source = ['a','b','c','d','e','f','g','h','i','j']
# turn it to generator
g = (i for i in source)
# create empty list
lines = []
# put what you want inside
for item in g:
if item=='c': # this can be replaced with .startswith()
lines.append(item)
for i in range(4):
lines.append(next(g))
In : lines
Out: ['c', 'd', 'e', 'f', 'g', 'h']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.