【问题标题】:Import CSV - Writing data to a file from the dictionary - Error导入 CSV - 将数据从字典写入文件 - 错误
【发布时间】:2019-08-06 01:30:16
【问题描述】:

我是 Python 新手。我正在尝试将一些数据写入 CSV 文件。我想从 Python 字典中写入文件

def write_info(self):
        fname='userinfo.csv'
        field_names = ['Username', 'Password']
        with open(fname, 'w') as op_file:
            op_writer = csv.DictWriter(op_file, fieldnames=field_names)
            op_writer.writeheader()
            **for row in self.user_dict:
                op_writer.writerow(row)**

你们能告诉我如何阅读字典并将其写入文件吗?当我打印字典 self.user_dict 时,我可以看到这些值。

当我看到

**for row in self.user_dict:
                op_writer.writerow(row)**

我得到了错误。

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-44-e1069dd9aafc> in <module>()
     28 
     29 # writing to file
---> 30 auth.write_info()

<ipython-input-44-e1069dd9aafc> in write_info(self)
     17             op_writer.writeheader()
     18             for row in self.user_dict:
---> 19                 op_writer.writerow(row)
     20 
     21        # fill in your code

~\AppData\Local\Continuum\anaconda3\lib\csv.py in writerow(self, rowdict)
    153 
    154     def writerow(self, rowdict):
--> 155         return self.writer.writerow(self._dict_to_list(rowdict))
    156 
    157     def writerows(self, rowdicts):

~\AppData\Local\Continuum\anaconda3\lib\csv.py in _dict_to_list(self, rowdict)
    146     def _dict_to_list(self, rowdict):
    147         if self.extrasaction == "raise":
--> 148             wrong_fields = rowdict.keys() - self.fieldnames
    149             if wrong_fields:
    150                 raise ValueError("dict contains fields not in fieldnames: "

**AttributeError: 'str' object has no attribute 'keys'**

【问题讨论】:

    标签: python-3.x dictionary export-to-csv


    【解决方案1】:

    self.user_dict 变量不包含字典。

    如你所愿,user_dict 应该是一个字典列表。

    user_dict = []
    user_dict.append({'username': 'joe', 'password': 'test'})
    user_dict.append({'username': 'doe', 'password': 'test'})
    

    【讨论】:

    • 谢谢。你是对的。我以上述格式创建了它,它可以工作。
    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    相关资源
    最近更新 更多