如何在Python中创建一个csv文件,并将其导出(放置)到某个本地目录 [英] How to create a csv file in Python, and export (put) it to some local directory

查看:54
本文介绍了如何在Python中创建一个csv文件,并将其导出(放置)到某个本地目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题可能很棘手.

我想从Python列表中创建一个csv文件.此csv文件以前不存在.然后将其导出到某个本地目录.本地目录中也没有这样的文件.我们只需创建一个新的csv文件,然后将csv文件导出(放入)本地目录中即可.

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.

我发现StringIO.StringIO可以从Python列表中生成csv文件,然后下一步是什么.

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

谢谢.

我发现以下代码可以做到:

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)

推荐答案

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

这篇关于如何在Python中创建一个csv文件,并将其导出(放置)到某个本地目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆