How to create a csv file in Python, and export (put) it to some local directory
Asked Answered
K

2

8

This problem may be tricky.

I want to create a csv file from a list in Python. This csv file does not 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 (put) the csv file in some local directory.

I found that StringIO.StringIO can generate the csv file from a list in Python, then what are the next steps.

Thank you.

And I found the following code can do it:

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)
Ki answered 25/9, 2014 at 0:19 Comment(4)
Why is this tricky? Show some initial effort and we can help you with more specific issues you might run into.Clench
Instead of writing the output to a StringIO instance, write it to an open()ed file.Stagemanage
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)Ki
I add the code as above. And it works. Can try.Ki
R
4
import csv

with open('/path/to/location', 'wb') as f:
  writer = csv.writer(f)
  writer.writerows(youriterable)

https://docs.python.org/2/library/csv.html#examples

Romy answered 25/9, 2014 at 0:24 Comment(0)
A
3

Did you read the docs?

https://docs.python.org/2/library/csv.html

Lots of examples on that page 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)
Antoinetteanton answered 25/9, 2014 at 0:24 Comment(2)
My concern is that here the "some.csv" file exists before I generate it. But I want to create a csv file, it does not exist on that path before I generate it.Ki
does the path not exist? You can use os.makedirs.Romy

© 2022 - 2024 — McMap. All rights reserved.