2

A list b is like:

X = [((a,b),12),((c,d),34),...]
for i in range(0,5):
    print X[i][0][0],X[i][1],X[i][0][1]

I want to save my data in a csv file. Eg. This can be saved as :

  • a,12,b- in first row (which is X[0][0][0], X[0][1])
  • c,34,d - in my second row and so on.

This is part of my project and I have no idea about .csv file.

What I did

writer= csv.writer(open('dict.csv','wb'))
for i in range(0,5):
    writer.writerow([x[i][0][0],x[i][1],x[i][0][1]])

But couldn't find anything in the csv file. How to fix it?

Community
  • 1
  • 1
SKY
  • 175
  • 2
  • 8

2 Answers2

2

You do not close the file:

f = open('dict.csv','wb')
writer= csv.writer(f)
for i in range(0,5):
    writer.writerow([x[i][0][0],x[i][1])
f.close() # close the file

Or better use the answer with the with statement:

with open('dict.csv','wb') as outfile:
    writer = csv.writer(outfile)
    for i in range(0,5):
        writer.writerow([x[i][0][0],x[i][1])
Community
  • 1
  • 1
Nander Speerstra
  • 1,496
  • 6
  • 24
  • 29
1

You were almost there.
while you write to csv , will default delimiter. So just provide the data that should be written to csv.

import csv
x= [(('a','b'),12),(('c','d'),34)]
writer= csv.writer(open('dict.csv','wb'))

for i in range(0,2):
    writer.writerow([x[i][0][0]]+[x[i][1]])

Check this for more info. https://docs.python.org/2/library/csv.html

sudheesh shetty
  • 358
  • 4
  • 14