我有一长串这样的表格——

a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]

也就是说,列表中的值是不同类型的——float,int, strings。我如何将它写入csv文件,使我的输出csv文件看起来像这样

1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2

当前回答

import csv
with open(file_path, 'a') as outcsv:   
    #configure writer to write standard csv file
    writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    writer.writerow(['number', 'text', 'number'])
    for item in list:
        #Write item to outcsv
        writer.writerow([item[0], item[1], item[2]])

官方文档:http://docs.python.org/2/library/csv.html

其他回答

在这个页面上甚至没有看到一个回答,包括如何包括头以及创建文件。这里有一种方法也包含了这一点。Method在python 3中工作得很好

csv_filename = 'abc.csv'
fieldnames = ['Col_1','Col_2','Col_3','Col_4']
with open(csv_filename, mode='w') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()
    for i in my_list:
        writer.writerow({fieldnames[0]: i[0], fieldnames[1]: i[1], fieldnames[2]: i[2],fieldnames[3]: i[3]}) 

使用csv。在我庞大的列表中,作者花了相当长的时间。我决定使用熊猫,它更快,更容易控制和理解:

 import pandas

 yourlist = [[...],...,[...]]
 pd = pandas.DataFrame(yourlist)
 pd.to_csv("mylist.csv")

好的部分是你可以改变一些东西来创建一个更好的csv文件:

 yourlist = [[...],...,[...]]
 columns = ["abcd","bcde","cdef"] #a csv with 3 columns
 index = [i[0] for i in yourlist] #first element of every list in yourlist
 not_index_list = [i[1:] for i in yourlist]
 pd = pandas.DataFrame(not_index_list, columns = columns, index = index)

 #Now you have a csv with columns and index:
 pd.to_csv("mylist.csv")

你可以用熊猫:

In [1]: import pandas as pd

In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]

In [3]: my_df = pd.DataFrame(a)

In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)

Python内置的CSV模块可以轻松处理:

import csv

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(a)

这假设你的列表被定义为a,就像你的问题一样。您可以通过CSV .writer()的各种可选参数调整输出CSV的确切格式,如上面链接的库参考页中所记录的那样。

Python 3更新

import csv

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(a)
import csv
with open(file_path, 'a') as outcsv:   
    #configure writer to write standard csv file
    writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    writer.writerow(['number', 'text', 'number'])
    for item in list:
        #Write item to outcsv
        writer.writerow([item[0], item[1], item[2]])

官方文档:http://docs.python.org/2/library/csv.html