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?
CodePudding user response:
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)
)
CodePudding user response:
This is a simple way without using any libraries.
import csv
my_list = [20.5, 21.7, 23.0, 23.6, 24.0, 24.7]
nth_line = 2 #--> You can give other values too.
with open('result.csv','w') as f:
for line in range(len(my_list)):
f.write(str(my_list[line]))
if (line 1) % nth_line == 0:
f.write('\n')
else:
f.write(', ')
CodePudding user response:
By re-shaping the list, then writing all at once:
import csv
data = [20.5, 21.7, 23.0, 23.6, 24.0, 24.7]
data = [data[x:x 2] for x in range(0, len(data), 2)]
with open("results.csv", "w") as f:
writer = csv.writer(f)
writer.writerows(data)
This will word for odd lengths as well:
# len = 7
data = [20.5, 21.7, 23.0, 23.6, 24.0, 24.7, 0]
results.csv
20.5,21.7
23.0,23.6
24.0,24.7
0
CodePudding user response:
I've come up with this solution that works in all cases:
from math import *
my_list = [20.5, 21.7, 23.0, 23.6, 24.0, 24.7]
values_per_line = 2
with open('result.csv','w') as f:
i = 0
number_of_lines = ceil(len(my_list)/values_per_line)
for line in range(number_of_lines):
for value in range(values_per_line):
if i < len(my_list)-1:
if value == (values_per_line - 1):
f.write("%s" % my_list[i])
else:
f.write("%s, " % my_list[i])
elif i == len(my_list)-1:
f.write("%s" % my_list[i])
i = i 1
if line != number_of_lines-1:
f.write("\n")
You can change the values_per_line to whatever you need.