How to create a csv file in Python and export (place) it to some local directory
This problem can be tricky.
I want to create a csv file from a list in Python. This csv file doesn't exist before. And then export it to some local directory. There is no such file in the local directory either. We just create a new csv file and export (place) the csv file to some local directory.
I found that StringIO.StringIO can generate a csv file from a list in Python, then what are the next steps.
Thank.
And I found the following code:
import os
import os.path
import StringIO
import csv
dir = r"C:\Python27"
if not os.path.exists(dir):
os.mkdir(dir)
my_list=[[1,2,3],[4,5,6]]
with open(os.path.join(dir, "filename"+'.csv'), "w") as f:
csvfile=StringIO.StringIO()
csvwriter=csv.writer(csvfile)
for l in my_list:
csvwriter.writerow(l)
for a in csvfile.getvalue():
f.writelines(a)
+3
source to share
2 answers
Have you read the docs?
https://docs.python.org/2/library/csv.html
This page provides many examples of how to read / write CSV files.
One of them:
import csv
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(someiterable)
0
source to share