我试图用Python列表中的值创建一个.csv文件。当我打印列表中的值时,它们都是unicode(?),即它们看起来像这样
[u'value 1', u'value 2', ...]
如果我遍历列表中的值,即mylist中的v:打印v,它们看起来是纯文本。
然后在每一个之间加上print '。join(mylist)
我可以输出到一个文件,即。
myfile = open(...)
print >>myfile, ','.join(mylist)
但是我想输出到CSV,并在列表中的值周围有分隔符。
"value 1", "value 2", ...
我找不到一个简单的方法来包括在格式分隔符,例如,我已经尝试通过连接语句。我该怎么做呢?
下面是Python 3的复制粘贴示例。使用选项定义自己的分隔符和引号字符。
import csv
mylist = ['value 1', 'value 2', 'value 3']
with open('employee_file.csv', mode='w') as employee_file:
employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
employee_writer.writerow(mylist)
这会生成employee_file.csv,如下所示:
"value 1","value 2","value 3"
NOTE:
If quoting is set to csv.QUOTE_MINIMAL, then .writerow() will quote
fields only if they contain the delimiter or the quotechar. This is
the default case.
If quoting is set to csv.QUOTE_ALL, then .writerow() will quote all
fields.
If quoting is set to csv.QUOTE_NONNUMERIC, then .writerow() will quote
all fields containing text data and convert all numeric fields to the
float data type.
If quoting is set to csv.QUOTE_NONE, then .writerow() will escape
delimiters instead of quoting them. In this case, you also must
provide a value for the escapechar optional parameter.
下面是另一个不需要csv模块的解决方案。
print ', '.join(['"'+i+'"' for i in myList])
例子:
>>> myList = [u'value 1', u'value 2', u'value 3']
>>> print ', '.join(['"'+i+'"' for i in myList])
"value 1", "value 2", "value 3"
但是,如果初始列表包含一些“,则不会转义。如果需要,可以调用一个函数像这样转义它:
print ', '.join(['"'+myFunction(i)+'"' for i in myList])