我正在尝试使用 Python 列表中的值创建一个 .csv 文件。当我打印列表中的值时,它们都是unicode(?),即它们看起来像这样
[u'value 1', u'value 2', ...]
如果我迭代列表中的值,即 for v in mylist: print v
它们看起来是纯文本。
我可以在每个之间放置一个 ,
print ','.join(mylist)
我可以输出到一个文件,即
myfile = open(...)
print >>myfile, ','.join(mylist)
但我想输出到 CSV 并且在列表中的值周围有分隔符,例如
"value 1", "value 2", ...
我找不到在格式中包含分隔符的简单方法,例如我已经尝试过 join
语句。我该怎么做?
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', ...]
If I iterate through the values in the list i.e. for v in mylist: print v
they appear to be plain text.
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)
But I want to output to a CSV and have delimiters around the values in the list e.g.
"value 1", "value 2", ...
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?
发布评论
评论(13)
编辑:这只适用于 python 2.x。
要使其与 python 3.x 一起使用,请将
wb
替换为w
(请参阅这个答案)Edit: this only works with python 2.x.
To make it work with python 3.x replace
wb
withw
(see this SO answer)这是 Alex Martelli 的安全版本:
Here is a secure version of Alex Martelli's:
对于另一种方法,您可以使用 DataFrame 在 pandas 中:
它可以轻松地将数据转储到 csv,就像下面的代码一样:
For another approach, you can use DataFrame in pandas:
And it can easily dump the data to csv just like the code below:
我发现的最佳选择是使用 savetxt ="noreferrer">
numpy
module:如果您有多个需要堆叠的列表
The best option I've found was using the
savetxt
from thenumpy
module:In case you have multiple lists that need to be stacked
使用 python 的 csv 模块读取和写入逗号或制表符分隔的文件。 csv 模块是首选,因为它可以让您很好地控制引用。
例如,这是为您提供的有效示例:
产生:
Use python's
csv
module for reading and writing comma or tab-delimited files. The csv module is preferred because it gives you good control over quoting.For example, here is the worked example for you:
Produces:
Jupyter 笔记本
假设您的列表名称是
A
那么您可以编写以下代码,并将其作为 csv 文件(仅限列!)
Jupyter notebook
Let's say that your list name is
A
Then you can code the following and you will have it as a csv file (columns only!)
在这种情况下,您可以使用 string.join 方法。
为了清楚起见,分成几行 - 这是一个交互式会话
或作为单行
但是,您可能会遇到一个问题,即您的字符串嵌入了引号。如果是这种情况,您需要决定如何逃脱它们。
CSV 模块 可以为您处理所有这一切,允许您在各种引用选项(所有字段、仅带引号和分隔符的字段、仅非数字字段等)以及如何转义控制字符(双引号或转义字符串)。如果您的值很简单,则 string.join 可能没问题,但如果您必须管理大量边缘情况,请使用可用的模块。
You could use the string.join method in this case.
Split over a few of lines for clarity - here's an interactive session
Or as a single line
However, you may have a problem is your strings have got embedded quotes. If this is the case you'll need to decide how to escape them.
The CSV module can take care of all of this for you, allowing you to choose between various quoting options (all fields, only fields with quotes and seperators, only non numeric fields, etc) and how to esacpe control charecters (double quotes, or escaped strings). If your values are simple, string.join will probably be OK but if you're having to manage lots of edge cases, use the module available.
这个解决方案听起来很疯狂,但工作起来很顺利。
文件是由 csvwriter 编写的,因此 csv 属性得到维护,即逗号分隔。
分隔符通过每次将列表项移动到下一行来帮助主要部分。
This solutions sounds crazy, but works smooth as honey
The file is being written by csvwriter hence csv properties are maintained i.e. comma separated.
The delimiter helps in the main part by moving list items to next line, each time.
这是 Python 3.x 的有效复制粘贴示例,其中包含定义您自己的分隔符和引号字符的选项。
这将生成如下所示的
employee_file.csv
:Here is working copy-paste example for Python 3.x with options to define your own delimiter and quote char.
This will generate
employee_file.csv
that looks like this:创建并写入 csv 文件
下面的示例演示了创建和写入 csv 文件。
要创建动态文件编写器,我们需要导入一个包导入 csv,然后需要使用文件引用创建该文件的实例
例如: - with open("D:\sample.csv","w",newline="") as file_writer
如果文件不存在于提到的文件目录中,那么 python 将创建一个指定目录中的同一个文件,“w”表示写入,如果要读取文件,请将“w”替换为“r”,或者附加到现有文件,然后“a”。 newline="" 指定每次创建行时都会删除一个额外的空行,因此为了消除空行,我们使用 newline="",使用 fields=["Names" 等列表创建一些字段名称(列名称) ,"Age","Class"],然后应用于 writer 实例,例如
writer=csv.DictWriter(file_writer,fieldnames=fields)
这里使用 Dictionary writer 并分配列名称,要将列名称写入 csv,我们使用 writer.writeheader() 并使用 writer.writerow({"Names":"John" ,"Age":20,"Class":"12A"}),写入文件值时必须使用字典的方式传递,这里的key是列名,value是你各自的key值
To create and write into a csv file
The below example demonstrate creating and writing a csv file.
to make a dynamic file writer we need to import a package import csv, then need to create an instance of the file with file reference
Ex:- with open("D:\sample.csv","w",newline="") as file_writer
here if the file does not exist with the mentioned file directory then python will create a same file in the specified directory, and "w" represents write, if you want to read a file then replace "w" with "r" or to append to existing file then "a". newline="" specifies that it removes an extra empty row for every time you create row so to eliminate empty row we use newline="", create some field names(column names) using list like fields=["Names","Age","Class"], then apply to writer instance like
writer=csv.DictWriter(file_writer,fieldnames=fields)
here using Dictionary writer and assigning column names, to write column names to csv we use writer.writeheader() and to write values we use writer.writerow({"Names":"John","Age":20,"Class":"12A"}) ,while writing file values must be passed using dictionary method , here the key is column name and value is your respective key value
对于那些寻找不太复杂的解决方案的人。实际上,我发现这是一个更简单的解决方案,可以完成类似的工作:
希望这也有帮助。
For those looking for less complicated solution. I actually find this one more simplisitic solution that will do similar job:
Hope this helps as well.
您肯定应该使用 CSV 模块,但很可能您需要编写 unicode。对于那些需要编写 unicode 的人,这是示例页面中的类,您可以将其用作 util 模块:
you should use the CSV module for sure , but the chances are , you need to write unicode . For those Who need to write unicode , this is the class from example page , that you can use as a util module:
这是另一个不需要
csv
模块的解决方案。示例:
但是,如果初始列表包含一些“,它们将不会被转义。如果需要,可以调用函数来转义它,如下所示:
Here is another solution that does not require the
csv
module.Example :
However, if the initial list contains some ", they will not be escaped. If it is required, it is possible to call a function to escape it like that :