Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to loop through blocks of lines

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
Age: 23

ID: 3
Name: S
FamilyN: Y
Age: 13

ID: 4
Name: M
FamilyN: Z
Age: 25

I want to loop through the blocks and grab the fields Name, Family name and Age in a list of 3 columns:

Y X 20
F H 23
Y S 13
Z M 25
like image 909
Adia Avatar asked Oct 12 '10 12:10

Adia


People also ask

How do you write a multi line for loop in Python?

Multi-line Statement in Python Usually, every Python statement ends with a newline character. However, we can extend it over to multiple lines using the line continuation character (\).

How do you write between lines in Python?

To add space in python between two lines or paragraphs we can use the new line character i.e “n”. # Using n to add space between two lines in python print("Hello World.

Can you iterate through a file python?

Yes, you can iterate through the file handle, no need to call readlines() . This way, on large files, you don't have to read all the lines (that's what readlines() does) at once.

How to loop numbers in Python?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.


1 Answers

Here's another way, using itertools.groupby. The function groupy iterates through lines of the file and calls isa_group_separator(line) for each line. isa_group_separator returns either True or False (called the key), and itertools.groupby then groups all the consecutive lines that yielded the same True or False result.

This is a very convenient way to collect lines into groups.

import itertools

def isa_group_separator(line):
    return line=='\n'

with open('data_file') as f:
    for key,group in itertools.groupby(f,isa_group_separator):
        # print(key,list(group))  # uncomment to see what itertools.groupby does.
        if not key:
            data={}
            for item in group:
                field,value=item.split(':')
                value=value.strip()
                data[field]=value
            print('{FamilyN} {Name} {Age}'.format(**data))

# Y X 20
# F H 23
# Y S 13
# Z M 25
like image 66
unutbu Avatar answered Oct 14 '22 00:10

unutbu