Skip to content
Advertisement

How can I loop through blocks of lines in a file?

I have a text file that looks like this, with blocks of lines separated by blank lines:

JavaScript

How can I loop through the blocks and process the data in each block? eventually I want to gather the name, family name and age values into three columns, like so:

JavaScript

Advertisement

Answer

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.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement