Kalimantan Kalimantan - 3 months ago 25
Python Question

Python: Line break after every nth line split

I want to force a line break after every 10 numbers or 9 nine splits on a txt file in python? How would I go about this? So say i have

Input would be something like:
40 20 30 50 40 40 40 40 40 40
20 40 20 30 50 40 40 40
20 40 20 30 50 40 40 40 40 20 20 20
20 20 20


int a txt.file
and output should be

40 20 30 50 40 40 40 40 40 40
20 40 20 30 50 40 40 40
20 40 20 30 50 40 40 40 40 20
20 20
20 20 20


so essentially break after every 10 numbers, or 9 line splits

I have tried:

with open('practice.txt') as f:

for line in f:
int_list = [int(num) for num in line.split() ]
if len(int_list) < 20:
print(int_list)
else:

new_list = int_list[20:]
int_list = int_list[:20]
print(int_list)
print(new_list)


But this doesn't quite solve it. Also note that the line lengths can vary. So the first line could have 5 numbers and the second line have 9 and the third 10 and the fourth 10

Answer

It looks like everything below the with statement should be indented one more level. Your method seems like a good start, but it will not work if there are more than 2 groups on one line. The following code takes care of that and simplifies things a bit:

with open('practice.txt') as f:
    values = []
    for line in f:
        int_list = [int(num) for num in line.split()]
        # the next line splits int_list into groups of 10 items, 
        # and appends all the groups to the values list
        values.extend(int_list[i:i+10] for i in range(0, len(int_list), 10))

print values
# [
#     [40, 20, 30, 50, 40, 40, 40, 40, 40, 40],
#     [20, 40, 20, 30, 50, 40, 40, 40],
#     [20, 40, 20, 30, 50, 40, 40, 40, 40, 20],
#     [20, 20],
#     [20, 20, 20]
# ]
Comments