这个问题可能很棘手。
我想用 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)
最佳答案
你读过文档了吗?
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)
关于python - 如何在 Python 中创建一个 csv 文件,并将其导出(放入)到某个本地目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26028555/