Python: How to loop through blocks of lines

后端 未结 10 1355
青春惊慌失措
青春惊慌失措 2020-11-29 07:42

How to go through blocks of lines separated by an empty line? The file looks like the following:

ID: 1
Name: X
FamilyN: Y
Age: 20

ID: 2
Name: H
FamilyN: F
A         


        
10条回答
  •  庸人自扰
    2020-11-29 08:27

    If file is not huge you can read whole file with:

    content = f.open(filename).read()
    

    then you can split content to blocks using:

    blocks = content.split('\n\n')
    

    Now you can create function to parse block of text. I would use split('\n') to get lines from block and split(':') to get key and value, eventually with str.strip() or some help of regular expressions.

    Without checking if block has required data code can look like:

    f = open('data.txt', 'r')
    content = f.read()
    f.close()
    for block in content.split('\n\n'):
        person = {}
        for l in block.split('\n'):
            k, v = l.split(': ')
            person[k] = v
        print('%s %s %s' % (person['FamilyN'], person['Name'], person['Age']))
    

提交回复
热议问题