簡體   English   中英

如何在Python中創建csv文件,並將其導出(放入)到某個本地目錄

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

這個問題可能很棘手。

我想從Python的列表中創建一個csv文件。 此csv文件之前不存在。 然后將其導出到某個本地目錄。 本地目錄中也沒有這樣的文件。 我們只是創建一個新的csv文件,並將csv文件導出(放入)在某個本地目錄中。

我發現StringIO.StringIO可以從Python中的列表生成csv文件,然后接下來的步驟是什么。

謝謝。

我發現以下代碼可以做到:

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)
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

你讀過文檔了嗎?

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

該頁面上有很多關於如何讀/寫CSV文件的例子。

其中之一:

import csv
with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM