如何在python中将列表转换为csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4622234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:33:45  来源:igfitidea点击:

How to convert a list to a csv in python

python

提问by carl stebbings

I have a list: ['1','2','3'] and want to convert it to 1,2,3 i.e. no brackets or quotation marks.

我有一个列表:['1','2','3'] 并希望将其转换为 1,2,3,即没有括号或引号。

回答by gravitation

",".join(lst)

will do it, but that's not really csv (would need escaping and such).

会这样做,但这并不是真正的 csv(需要转义等)。

回答by asthasr

If you want to generate a canonical CSV file, use the csvmodule.

如果要生成规范的 CSV 文件,请使用csv模块。



Example from the docs:

文档中的示例:

>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'wb'), delimiter=' ',
...                         quotechar='|', quoting=csv.QUOTE_MINIMAL)
>>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
>>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

回答by Hugh Bothwell

import csv

def writeCsvFile(fname, data, *args, **kwargs):
    """
    @param fname: string, name of file to write
    @param data: list of list of items

    Write data to file
    """
    mycsv = csv.writer(open(fname, 'wb'), *args, **kwargs)
    for row in data:
        mycsv.writerow(row)

mydat = (
    ['Name','Age','Grade'],
    ['Teri', 14, 7],
    ['John', 8, 2]
)

writeCsvFile(r'c:\test.csv', mydat)

回答by mguillech

Carl, whenever you write data into a file what Python actually does is buffer the data and then does its I/O operation with the file (writing the data into the file). This operation is called 'flushing' (the buffers). You have to make sure you are close()ing the opened file, if not, buffer won't be flushed and thus you won't have anything written in the file.

Carl,每当您将数据写入文件时,Python 实际上所做的是缓冲数据,然后对文件进行 I/O 操作(将数据写入文件)。此操作称为“刷新”(缓冲区)。您必须确保关闭()打开打开的文件,否则,缓冲区将不会被刷新,因此您将不会在文件中写入任何内容。

回答by burmer

I think you need to split out the file opening part of your code so that you can close that later, separately. In this case, you are trying to "close" the writer object. Although the better way is to use "with", this example is more similar to the way you have it:

我认为您需要拆分代码的文件打开部分,以便稍后可以单独关闭它。在这种情况下,您正在尝试“关闭”编写器对象。虽然更好的方法是使用“with”,但这个例子更类似于你使用它的方式:

csvfile = open('test.csv', 'wb')
csvwriter = csv.writer(csvfile)
for item in pct:
    csvwriter.writerow(item)
csvfile.close()

回答by Prince Mathur

You can convert almost any list to csv using pandas like this:

您可以使用如下所示的 Pandas 将几乎任何列表转换为 csv:

import pandas as pd    

list1 = [1,2,3,4,5]
df = pd.DataFrame(list1)

Depending on what you want to do with this csv, you can either keep the csv in a variable:

根据你想用这个 csv 做什么,你可以将 csv 保存在一个变量中:

csv_data = df.to_csv(index=False)

Or save it in your filesystem like this:

或者像这样将它保存在你的文件系统中:

df.to_csv('filename.csv', index=False)

Here index=Falsewill remove unnecessary indexing/numbering in your csv.

这里index=False将删除 csv 中不必要的索引/编号。