簡體   English   中英

Python閱讀從文本文件向列表添加多一行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM