ABHI MISHRA ABHI MISHRA - 1 year ago 101
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,04 ... and so on

this is what i coded:

with open('datas.csv','w')as f:
for value in sec_min:

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

Answer Source

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.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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download