Python: How to loop through blocks of lines

后端 未结 10 1360
青春惊慌失措
青春惊慌失措 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:36

    Along with the half-dozen other solutions I already see here, I'm a bit surprised that no one has been so simple-minded (that is, generator-, regex-, map-, and read-free) as to propose, for example,

    fp = open(fn)
    def get_one_value():
        line = fp.readline()
        if not line:
            return None
        parts = line.split(':')
        if 2 != len(parts):
            return ''
        return parts[1].strip()
    
    # The result is supposed to be a list.
    result = []
    while 1:
            # We don't care about the ID.
       if get_one_value() is None:
           break
       name = get_one_value()
       familyn = get_one_value()
       age = get_one_value()
       result.append((name, familyn, age))
           # We don't care about the block separator.
       if get_one_value() is None:
           break
    
    for item in result:
        print item
    

    Re-format to taste.

提交回复
热议问题