ML2019
ML2019

Reputation: 71

Import CSV - Writing data to a file from the dictionary - Error

I am new to Python.I am trying to write some data to a CSV file.I want to write to a file from a dictionary in 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)**

Can you guys tell me how to read the dictionary and write it to the file. When I print the dictionary self.user_dict I can see the values.

When I see the

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

and I get the error.

---------------------------------------------------------------------------
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'**

Upvotes: 1

Views: 56

Answers (1)

Josir
Josir

Reputation: 1644

self.user_dict variable does not contain a dict.

The way you want it, user_dict should be a list of dicts.

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

Upvotes: 1

Related Questions