ABHI MISHRA ABHI MISHRA - 2 months ago 18
Python Question

How to write nth value of list into csv file

i have the following list :

sec_min=['37', '01', '37', '02', '37', '03', '37', '04', '37', '05',....]


i want to store this list into CVS file in following format:

37,01
37,02
37,03
37,04 ... and so on


this is what i coded:

with open('datas.csv','w')as f:
data=csv.writer(f)
for value in sec_min:
data.writerow(sec_min[:2])


(i.e. every two elements of list in new row)

Answer

compose a "matrix" of row length = 2, and write all the rows at once.

with open('datas.csv','wb') as f:  # python 2
with open('datas.csv','w',newline='') as f:  # python 3

   data=csv.writer(f)
   data.writerows([sec_min[l:l+2] for l in range(0,len(sec_min),2)])

note the different way of opening a file for csv module whether you're running python 2 or python 3.

Your original method results in blank lines every other line because of extra \r chars.