-1

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)

Abhishek
  • 333
  • 4
  • 12

1 Answers1

1

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

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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219