Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 310
user3634601 Avatar asked Sep 25 '14 00:09

user3634601


People also ask

How do I save a CSV file to a specific location in Python?

to_csv(path='D:\My_Path\High. csv') elif (X1<55 and X2<55 and X3<55 and X4<55): df. to_csv(path='D:\My_Path\Low. csv') else: print("Ignore") ...

How do I create a local csv file?

Microsoft ExcelOnce open, click File and choose Save As. Under Save as type, select CSV (Comma delimited) or CSV (Comma delimited) (*. csv), depending on your version of Microsoft Excel. The last row begins with two commas because the first two fields of that row were empty in our spreadsheet.


1 Answers

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

like image 174
corvid Avatar answered Nov 02 '22 20:11

corvid