Reputation: 1889
I have this data -
data = [[(1,2)], [(1,2)], [(1,2)]]
The tuples inside the inner list are co-ordinates.
I've tried this -
>>> with open("file.csv", "wb") as afile:
... writer = csv.writer(afile)
... writer.writerows(data)
The file contains this output -
"(1, 2)"
"(1, 2)"
"(1, 2)"
I tried reading from this file using this -
print [row for row in csv.reader(open("file.csv", "rb"))]
Gave me []
And there can be multiple tuples in the inner list.
How can I write this to file as csv, such that another python program can read it?
Upvotes: 0
Views: 657
Reputation: 123473
I think this might be what you want. I changed to data to have more than one tuple on one of the inner lists and have more unique values to aid troubleshooting. The important point is that you must pass writerows()
a sequence of strings or numbers (or apparently a generator expression producing such things).
import csv
data = [[(1,1)], [(1,2), (3,4)], [(1,3)]]
with open("file.csv", "wb") as afile:
writer = csv.writer(afile)
writer.writerows((coord for coord in data))
print [row for row in csv.reader(open("file.csv", "rb"))]
Output:
[['(1, 1)'], ['(1, 2)', '(3, 4)'], ['(1, 3)']]
Upvotes: 1
Reputation: 7177
Perhaps something like this?
#!/usr/local/cpython-3.3/bin/python
import csv
data = [[(1,2)], [(1,2)], [(1,2)]]
with open("file.csv", "w") as afile:
writer = csv.writer(afile)
for sublist in data:
writer.writerow(sublist[0])
Upvotes: 1