簡體   English   中英

在 csv - python 中使用打印格式不適用於 DictWriter

[英]Using print format doesn't work for DictWriter in csv - python

下面的例子似乎不起作用

import csv

values = [{'emp_name': 'John Wick',
        'dept': 'Accounting', 'val': '10'},
       {'emp_name': 'Neo Anderson',
        'dept': 'IT', 'val': '20'}]

with open('file1.csv', mode='w') as csv_file:
    fieldnames = ['name', 'department']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    for value in values:
        writer.writerow({"'name': '{emp_name}', 'department': '{dept}'".format(
            **value)
        })

錯誤:

Traceback (most recent call last):
  File "csv_test.py", line 13, in <module>
    **value)
  File "python-3.7.5/lib/python3.7/csv.py", line 155, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "python-3.7.5/lib/python3.7/csv.py", line 148, in _dict_to_list
    wrong_fields = rowdict.keys() - self.fieldnames
AttributeError: 'set' object has no attribute 'keys'

預期 Output:

name, department
John Wick, Accounting
Neo Anderson, IT

有沒有好的解決方法?

使用writerow時使用傳遞dict

前任:

import csv

values = [{'emp_name': 'John Wick',
        'dept': 'Accounting'},
       {'emp_name': 'Neo Anderson',
        'dept': 'IT'}]

with open('file1.csv', mode='w') as csv_file:
    fieldnames = ['emp_name', 'dept']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    for value in values:
        writer.writerow({"emp_name": value['emp_name'], "dept": value['dept']})   #Pass the dict



    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM