简体   繁体   中英

python search key and read line after matching and send to list

I have file output like below

some junk text
ignore above text
pen: 4
apple: 10
orange: 20
pen: 30
apple: 40
bat: 20
ball: 300
football: 500
pencil: 200
again junk test ignore it

Requirement:

Search keyword in file and send next 10 lines output to list1 as values

I tried below code but not working. Need your help to achieve results.

from itertools import islice
list1 = []
with open ("file.txt") as fin:
    for line in fin:
        if line.startswith("ignore above text"):
            list1 = (islice(fin,9))
            print list1

Expected output:

 list1 = ['pen: 4','apple: 10','orange: 20',pen: 30','apple: 40','bat: 20','ball: 300', 'football: 500', 'pencil']

You need to convert it to a list (or a tuple):

list1 = list((islice(fin,9)))
#         ^

Otherwise it is just a generator which gives you the next value if asked. However, you might as well stick to the generator and iterate over it afterwards:

for item in list1:
    print(item.strip())
    # or anything else

So your code might become:

from itertools import islice
with open("test.txt") as fp:
    for line in fp:
        if line.startswith('ignore above text'):
            for item in islice(fp, 9):
                print(item.strip())

Generators are an extremely useful and often used mechanism in Python , you might want to read sth. about them here .

You can try the code below:

file_with_data = open("file.txt", "r")
raw_data = file_with_data.read()
file_with_data.close()

input_data_as_list = raw_data.split("\n")
output_data = []
for i in range(len(input_data_as_list)):
    if input_data_as_list[i] == "ignore above text":
        output_data = input_data_as_list[i+1:i+10]
        break

print(output_data)
 mystr=open("your\\file\\path").read()
 my_list=mystr.split("\n")
 my_list=[item for item in my_list if not item.startswith("ignore")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM