使用 Python 列表中的值创建 .csv 文件

发布于 2024-08-17 19:51:35 字数 532 浏览 6 评论 0 原文

我正在尝试使用 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

往日 2024-08-24 19:51:35
import csv

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

编辑:这只适用于 python 2.x。

要使其与 python 3.x 一起使用,请将 wb 替换为 w (请参阅这个答案

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

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

Edit: this only works with python 2.x.

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)
空气里的味道 2024-08-24 19:51:35

这是 Alex Martelli 的安全版本:

import csv

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

Here is a secure version of Alex Martelli's:

import csv

with open('filename', 'wb') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(mylist)
残花月 2024-08-24 19:51:35

对于另一种方法,您可以使用 DataFramepandas 中:
它可以轻松地将数据转储到 csv,就像下面的代码一样:

import pandas
df = pandas.DataFrame(data={"col1": list_1, "col2": list_2})
df.to_csv("./file.csv", sep=',',index=False)

For another approach, you can use DataFrame in pandas:
And it can easily dump the data to csv just like the code below:

import pandas
df = pandas.DataFrame(data={"col1": list_1, "col2": list_2})
df.to_csv("./file.csv", sep=',',index=False)
夏末 2024-08-24 19:51:35

我发现的最佳选择是使用 savetxt ="noreferrer">numpy module

import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)

如果您有多个需要堆叠的列表

np.savetxt("file_name.csv", np.column_stack((data1, data2)), delimiter=",", fmt='%s', header=header)

The best option I've found was using the savetxt from the numpy module:

import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)

In case you have multiple lists that need to be stacked

np.savetxt("file_name.csv", np.column_stack((data1, data2)), delimiter=",", fmt='%s', header=header)
可爱暴击 2024-08-24 19:51:35

使用 python 的 csv 模块读取和写入逗号或制表符分隔的文件。 csv 模块是首选,因为它可以让您很好地控制引用。

例如,这是为您提供的有效示例:

import csv
data = ["value %d" % i for i in range(1,4)]

out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(data)

产生:

"value 1","value 2","value 3"

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:

import csv
data = ["value %d" % i for i in range(1,4)]

out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(data)

Produces:

"value 1","value 2","value 3"
别在捏我脸啦 2024-08-24 19:51:35

Jupyter 笔记本

假设您的列表名称是 A

那么您可以编写以下代码,并将其作为 csv 文件(仅限列!)

R="\n".join(A)
f = open('Columns.csv','w')
f.write(R)
f.close()

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!)

R="\n".join(A)
f = open('Columns.csv','w')
f.write(R)
f.close()
画中仙 2024-08-24 19:51:35

在这种情况下,您可以使用 string.join 方法。

为了清楚起见,分成几行 - 这是一个交互式会话

>>> a = ['a','b','c']
>>> first = '", "'.join(a)
>>> second = '"%s"' % first
>>> print second
"a", "b", "c"

或作为单行

>>> print ('"%s"') % '", "'.join(a)
"a", "b", "c"

但是,您可能会遇到一个问题,即您的字符串嵌入了引号。如果是这种情况,您需要决定如何逃脱它们。

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

>>> a = ['a','b','c']
>>> first = '", "'.join(a)
>>> second = '"%s"' % first
>>> print second
"a", "b", "c"

Or as a single line

>>> print ('"%s"') % '", "'.join(a)
"a", "b", "c"

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.

难以启齿的温柔 2024-08-24 19:51:35

这个解决方案听起来很疯狂,但工作起来很顺利。

import csv

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

文件是由 csvwriter 编写的,因此 csv 属性得到维护,即逗号分隔。
分隔符通过每次将列表项移动到下一行来帮助主要部分。

This solutions sounds crazy, but works smooth as honey

import csv

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

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.

就是爱搞怪 2024-08-24 19:51:35

这是 Python 3.x 的有效复制粘贴示例,其中包含定义您自己的分隔符和引号字符的选项。

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"

注意:

如果引用设置为 csv.QUOTE_MINIMAL,则 .writerow() 将引用
仅当字段包含分隔符或引号字符时。这是
默认情况。

如果引用设置为 csv.QUOTE_ALL,则 .writerow() 将引用所有内容
字段。

如果引用设置为 csv.QUOTE_NONNUMERIC,则 .writerow() 将引用
所有包含文本数据的字段并将所有数字字段转换为
浮点数据类型。

如果引用设置为 csv.QUOTE_NONE,则 .writerow() 将转义
分隔符而不是引用它们。在这种情况下,您还必须
为 escapechar 可选参数提供一个值。

Here is working copy-paste example for Python 3.x with options to define your own delimiter and quote char.

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)

This will generate employee_file.csv that looks like this:

"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.

挽清梦 2024-08-24 19:51:35

创建并写入 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值

import csv 

with open("D:\\sample.csv","w",newline="") as file_writer:

   fields=["Names","Age","Class"]

   writer=csv.DictWriter(file_writer,fieldnames=fields)

   writer.writeheader()

   writer.writerow({"Names":"John","Age":21,"Class":"12A"})

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

import csv 

with open("D:\\sample.csv","w",newline="") as file_writer:

   fields=["Names","Age","Class"]

   writer=csv.DictWriter(file_writer,fieldnames=fields)

   writer.writeheader()

   writer.writerow({"Names":"John","Age":21,"Class":"12A"})
山色无中 2024-08-24 19:51:35

对于那些寻找不太复杂的解决方案的人。实际上,我发现这是一个更简单的解决方案,可以完成类似的工作:

import pandas as pd
a = ['a','b','c'] 
df = pd.DataFrame({'a': a})
df= df.set_index('a').T
df.to_csv('list_a.csv', index=False)

希望这也有帮助。

For those looking for less complicated solution. I actually find this one more simplisitic solution that will do similar job:

import pandas as pd
a = ['a','b','c'] 
df = pd.DataFrame({'a': a})
df= df.set_index('a').T
df.to_csv('list_a.csv', index=False)

Hope this helps as well.

っ左 2024-08-24 19:51:35

您肯定应该使用 CSV 模块,但很可能您需要编写 unicode。对于那些需要编写 unicode 的人,这是示例页面中的类,您可以将其用作 util 模块:

import csv, codecs, cStringIO

class UTF8Recoder:
    """
    Iterator that reads an encoded stream and reencodes the input to UTF-8
    """
    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)

def __iter__(self):
    return self

def next(self):
    return self.reader.next().encode("utf-8")

class UnicodeReader:
    """
    A CSV reader which will iterate over lines in the CSV file "f",
    which is encoded in the given encoding.
    """

def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
    f = UTF8Recoder(f, encoding)
    self.reader = csv.reader(f, dialect=dialect, **kwds)

def next(self):
    row = self.reader.next()
    return [unicode(s, "utf-8") for s in row]

def __iter__(self):
    return self

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
"""

def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
    # Redirect output to a queue
    self.queue = cStringIO.StringIO()
    self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
    self.stream = f
    self.encoder = codecs.getincrementalencoder(encoding)()

def writerow(self, row):
    self.writer.writerow([s.encode("utf-8") for s in row])
    # Fetch UTF-8 output from the queue ...
    data = self.queue.getvalue()
    data = data.decode("utf-8")
    # ... and reencode it into the target encoding
    data = self.encoder.encode(data)
    # write to the target stream
    self.stream.write(data)
    # empty queue
    self.queue.truncate(0)

def writerows(self, rows):
    for row in rows:
        self.writerow(row)

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:

import csv, codecs, cStringIO

class UTF8Recoder:
    """
    Iterator that reads an encoded stream and reencodes the input to UTF-8
    """
    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)

def __iter__(self):
    return self

def next(self):
    return self.reader.next().encode("utf-8")

class UnicodeReader:
    """
    A CSV reader which will iterate over lines in the CSV file "f",
    which is encoded in the given encoding.
    """

def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
    f = UTF8Recoder(f, encoding)
    self.reader = csv.reader(f, dialect=dialect, **kwds)

def next(self):
    row = self.reader.next()
    return [unicode(s, "utf-8") for s in row]

def __iter__(self):
    return self

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
"""

def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
    # Redirect output to a queue
    self.queue = cStringIO.StringIO()
    self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
    self.stream = f
    self.encoder = codecs.getincrementalencoder(encoding)()

def writerow(self, row):
    self.writer.writerow([s.encode("utf-8") for s in row])
    # Fetch UTF-8 output from the queue ...
    data = self.queue.getvalue()
    data = data.decode("utf-8")
    # ... and reencode it into the target encoding
    data = self.encoder.encode(data)
    # write to the target stream
    self.stream.write(data)
    # empty queue
    self.queue.truncate(0)

def writerows(self, rows):
    for row in rows:
        self.writerow(row)
甩你一脸翔 2024-08-24 19:51:35

这是另一个不需要 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])

Here is another solution that does not require the csv module.

print ', '.join(['"'+i+'"' for i in myList])

Example :

>>> myList = [u'value 1', u'value 2', u'value 3']
>>> print ', '.join(['"'+i+'"' for i in myList])
"value 1", "value 2", "value 3"

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 :

print ', '.join(['"'+myFunction(i)+'"' for i in myList])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文