How to grab the lines AFTER a matched line in python

前端 未结 4 1312
[愿得一人]
[愿得一人] 2021-01-05 12:22

I am an amateur using Python on and off for some time now. Sorry if this is a silly question, but I was wondering if anyone knew an easy way to grab a bunch of lines if the

4条回答
  •  难免孤独
    2021-01-05 13:25

    Other than a generator, I think we can create a dict where the key is "Heading" and the value is one list to save the lines. Here is the code

    odd_map = {}
    odd_list = []
    with open(file, 'r') as myFile:
        lines = myFile.readlines()
        for line in lines:
            if "Heading" in line:
                odd_list = []
                odd_map[line.strip()] = odd_list
            else:    
                odd_list.append(line.strip())
    
    for company, odds in odd_map.items():
        print(company)
        for odd in odds:
            print(odd)
    

提交回复
热议问题