Concatenating strings from multiple rows into a file separated by new rows

advertisements

If I have a file with multiple lines like:

name1
12345
67890

name2
23456
78901

name3
34567
89012

How would I go about concatenating each line in the form:

"name1 1234567890"

"name2 2345678901"

"name3 3456789012"

Specifically, what is the best way to concatenate strings from a file into a single line until an empty line is encountered?


You can split first with \n\n and then split \n to get each item.

data = open('file_name').read()

output = ["%s %s%s" % tuple(item.split('\n')) for item in data.split('\n\n')]

['name1 1234567890', 'name2 2345678901', 'name3 3456789012']