Reputation: 81
Example Lines from txt file:
one
two
three
one1
two2
three3
Desired result:
['one', 'two', 'three']
['one1', 'two2', 'three3']
How can I combine every 3 lines into 1 and convert to list?
I would like this to continue through a large text file with hundreds of lines.
This code I took from another thread bu it only combines 2 per line
f = open('joining-lines-template.txt')
mod_list = []
count = 1
for line in f:
line = line.rstrip()
if count % 2 == 0:
mod_list.append(old_line+line)
else:
old_line = line
count += 1
print(mod_list)
CLARIFICATION
The final output when printed should look like below, with lists on new lines rather than all on the one line.
['one', 'two', 'three']
['one1', 'two2', 'three3']
Upvotes: 0
Views: 752
Reputation: 140168
I would read the file fully, then create a list comprehension with slicing 3 by 3:
with open("input.txt") as f:
lines = list(f) # convert file to list of lines so slicing works
result = [lines[i:i+3] for i in range(0,len(lines),3) ]
Variant: here's a way which doesn't need to read all the file at once:
with open("input.txt") as f:
result = [[l,next(f),next(f)] for l in f]
But saving memory has a price:
beginners may like a full "classical" python code:
result = []
sublist = []
for l in f:
sublist.append(l)
if len(sublist)==3:
result.append(sublist)
sublist = []
if sublist:
result.append(sublist)
in all cases to print the list of lists as you need just to:
for l in result:
print(l) # prints the representation of the sublist
Upvotes: 2