使用 Python 列表中的值创建 .csv 文件 [英] Create a .csv file with values from a Python list

查看:44
本文介绍了使用 Python 列表中的值创建 .csv 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python 列表中的值创建一个 .csv 文件.当我打印列表中的值时,它们都是 unicode (?),即它们看起来像这样

I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this

[u'value 1', u'value 2', ...]

如果我遍历列表中的值,即 for v in mylist: print v 它们看起来是纯文本.

If I iterate through the values in the list i.e. for v in mylist: print v they appear to be plain text.

我可以在每个之间加上 ,print ','.join(mylist)

And I can put a , between each with print ','.join(mylist)

我可以输出到一个文件,即

And I can output to a file, i.e.

myfile = open(...)
print >>myfile, ','.join(mylist)

但我想输出到 CSV 并在列表中的值周围使用分隔符,例如

But I want to output to a CSV and have delimiters around the values in the list e.g.

"value 1", "value 2", ... 

我找不到在格式中包含分隔符的简单方法,例如我已经尝试过 join 语句.我该怎么做?

I can't find an easy way to include the delimiters in the formatting, e.g. I have tried through the join statement. How can I do this?

推荐答案

import csv

with open(..., 'wb') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(mylist)

这只适用于 python 2.x.

this only works with python 2.x.

为了使其与 python 3.x 一起工作,将 wb 替换为 w (看到这个答案)

To make it work with python 3.x replace wb with w (see this SO answer)

with open(..., 'w', newline='') as myfile:
     wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
     wr.writerow(mylist)

这篇关于使用 Python 列表中的值创建 .csv 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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