I want to write three separate text files for each three element of the list below:
my_list = ['text1', 'text1', 'text1', 'text2', 'text2', 'text2', 'text3', 'text3', 'text3']
result = [my_list[idx:idx + 3] for idx in range(0, len(my_list), 3)]
outfiles = ['file1', 'file2', 'file3']
for f in outfiles:
with open ('{}.txt'.format(f),'w') as fo:
for x in result:
for y in x:
fo.write(str(y) + '\n')
Please help me correcting the code above.
file1 should consist:
text1
text1
text1
file2:
text2
text2
text2
file3:
text3
text3
text3
But my code above writes:
text1
text1
text1
text2
text2
text2
text3
text3
text3
The following can be done with minimal edits to your code:
You can try this using a loop to iterate over a slice of the list. Here, we are using the variable
i
to indicate which slice of the list will be used in each iteration:I would probably use
itertools.groupby
here ...This assumes that the initial list was sorted and it seems a little silly to write the same thing to a file over and over, but if you really have a more diverse list, you can always sort and group by the result of some key function which would be applied to each element in the list...