I have a list that contains numbers like this:
[20.5, 21.7, 23.0, 23.6, 24.0, 24.7]
and i want to write the list to a csv file that should look like this:
20.5, 21.7
23.0, 23.6
24.0, 24.7
so every second line in my list should be written to the next row in the csv file.
right now my script just looks like this:
import csv
with open('result.csv','w') as f:
for line in my_list:
f.write("%s\n" % line)
how can i write only every nth line as a new line and every nth line as new row?
>Solution :
If you don’t need the space after the comma:
import csv
data = [20.5, 21.7, 23.0, 23.6, 24.0, 24.7]
with open('result.csv','w') as file:
csv.writer(file).writerows(data[i:i + 2] for i in range(0, len(data), 2))
Otherwise:
with open('result.csv','w') as file:
file.writelines(
", ".join(map(str, data[i:i + 2])) + "\n" for i in range(0, len(data), 2)
)