繁体   English   中英

用Python将字典写入csv的最有效方法是什么?

[英]What is the most efficient way of writing a dictionary into a csv in Python?

我正在编写代码,通过从网站抓取html表来生成csv文件。 该函数将查看表<tr>每一行,并将数据列存储在如下所示的字典中

 def write_data():
    table_date = get_data()   # call function to get data from html table into a dict
    // write table_date to csv

 def get_data():
   data = {}
   for row in tr:
      data['name'] = 'John'
      data['id'] = 12
      return data

这是一个简化的版本,但从本质上讲,我需要一种获取每个表行的字典对象data并将其写入csv(其中键为标题行)的方法。 什么是有效的方法?

使用csv.DictWriter() 只需将字典发送给每一行:

writer = csv.DictWriter(open_writable_file, fieldnames=['id', 'name'])
writer.writeheader()  # write a row the fieldnames

并为您制作的每本词典:

writer.writerow(table_data)

确保使用newline=''选项打开可写文件,以使csv模块控制行尾:

with open(filename, 'w', newline='') as open_writable_file):

由于某些原因, csv.DictWriter文档示例中省略了此建议。 但该对象是csv.writer()的子类,并且那里的建议也同样适用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM