I am trying make script that split text file with lines into multiple lines group in python3 here is an example:
text file contains:
1
2
3
4
5
6
7
8
9
10
output that I want:
first chunk
1
2
3
second chunk
4
5
6
third chunk
7
8
9
fourth chunk
10
how can I do that? and thank you in advance
CodePudding user response:
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i n]
with open(path_to_txt_file) as f:
arr = f.read().splitlines()
divide_chunks(arr, 3)
which gives (as generator):
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['10']]