【问题标题】:What is the most efficient way of writing a dictionary into a csv in Python?在 Python 中将字典写入 csv 的最有效方法是什么?
【发布时间】:2016-03-10 07:49:16
【问题描述】:

我正在编写代码以通过从网站上抓取 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,其中的键将是标题行。有什么有效的方法来做到这一点?

【问题讨论】:

    标签: python csv python-3.x dictionary file-io


    【解决方案1】:

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

    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() class 的子类,那里的建议同样适用。

    【讨论】:

    • 感谢@martinj,这有帮助。虽然我有几个问题? 1.有没有办法从字典键本身获取文件名,而不必显式编写? 2. 另外,return 语句只会返回第一行并停止,但我需要将 get_data() 中的每一行返回到 write_data() 函数。有没有办法做到这一点?
    • 您明确编写它们以定义它们的顺序。字典没有明确的顺序。你可以只使用第一个字典中的table_data.keys(),但是你会得到一个不一致的顺序(这将取决于 Python 用来避免哈希冲突攻击的随机种子)。
    • 我不知道您是如何抓取数据的;您可以使用生成器函数从函数中生成更多行数据,或者只返回它们的列表,或者让函数直接写入 CSV 文件。
    猜你喜欢
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    相关资源
    最近更新 更多