Answers:
import csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(toCSV)
编辑:我以前的解决方案不处理订单。正如Wilduck所指出的,此处DictWriter更合适。
with open('people.csv', 'wb') as f: ...
dict_writer.writeheader()
,而不是dict_writer.writer.writerow(keys)
open('people.csv', 'w')
set().union(*(d.keys() for d in mylist))
以获得列表中的所有键(如果您有一些不具备所有键的键。)
在python 3中,情况有所不同,但是方式更简单,错误更少。最好告诉CSV文件应使用utf8
编码打开,因为这会使数据更易于其他人使用(假设您未使用限制性更强的编码,例如latin1
)
import csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
with open('people.csv', 'w', encoding='utf8', newline='') as output_file:
fc = csv.DictWriter(output_file,
fieldnames=toCSV[0].keys(),
)
fc.writeheader()
fc.writerows(toCSV)
csv
在python 3中需要该newline=''
参数,否则在excel / opencalc中打开时,CSV中会出现空白行。或者:我更喜欢在pandas
模块中使用csv处理程序。我发现它对编码问题的容忍度更高,并且熊猫在加载文件时会自动将CSV中的字符串数字转换为正确的类型(int,float等)。
import pandas
dataframe = pandas.read_csv(filepath)
list_of_dictionaries = dataframe.to_dict('records')
dataframe.to_csv(filepath)
注意:
utf8
python3中的名称,并且找出标头。dataframe.to_dict('records')
csv
模块,您需要将其喂入,OrderedDict
否则它们将以随机顺序出现(如果在python <3.5中工作)。有关更多信息,请参见:在Python Pandas DataFrame中保留列顺序。因为@User和@BiXiC在这里寻求UTF-8的帮助,所以@Matthew提供了解决方案的变体。(不允许发表评论,所以我在回答。)
import unicodecsv as csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(toCSV)
这是另一个更通用的解决方案,假设您没有行列表(也许它们不适合内存)或标题的副本(也许write_csv
函数是通用的):
def gen_rows():
yield OrderedDict(name='bob', age=25, weight=200)
yield OrderedDict(name='jim', age=31, weight=180)
def write_csv():
it = genrows()
first_row = it.next() # __next__ in py3
with open("people.csv", "w") as outfile:
wr = csv.DictWriter(outfile, fieldnames=list(first_row))
wr.writeheader()
wr.writerow(first_row)
wr.writerows(it)
注意:这里使用的OrderedDict构造函数仅在python> 3.4中保留顺序。如果订单很重要,请使用OrderedDict([('name', 'bob'),('age',25)])
表格。
import csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
header=['name','age','weight']
try:
with open('output'+str(date.today())+'.csv',mode='w',encoding='utf8',newline='') as output_to_csv:
dict_csv_writer = csv.DictWriter(output_to_csv, fieldnames=header,dialect='excel')
dict_csv_writer.writeheader()
dict_csv_writer.writerows(toCSV)
print('\nData exported to csv succesfully and sample data')
except IOError as io:
print('\n',io)