Home > Mobile >  Creating dictionary file using a csv file in python
Creating dictionary file using a csv file in python

Time:10-30

import csv

keys = ["id", "name", "age", "height", "weight"]
 
with open('temp.csv', 'w') as temp_file:
    dict_writer_obj = csv.DictWriter(temp_file, fieldnames = keys) 
    
    with open('dictReader.csv','r') as file:
        dict_reader_obj = csv.DictReader(file) 
        
        dict_writer_obj.writeheader()
        dict_writer_obj.writerows(file)

I want to convert a csv file called dictReader.csv file into dictionary based file: However I am getting the following error. Any ideas? AttributeError: 'str' object has no attribute 'keys'

My dictReader.csv file content:

id,name,age,height,weight
1,Alice,20,62,120.6
2,Freddie,21,74,190.6
3,Bob,17,68,120.0

Desired output file called temp.csv with this format


{'id': '1', 'name': 'Alice', 'age': '20', 'height': '62', 'weight': '120.6'}
{'id': '2', 'name': 'Freddie', 'age': '21', 'height': '74', 'weight': '190.6'}
{'id': '3', 'name': 'Bob', 'age': '17', 'height': '68', 'weight': '120.0'}

CodePudding user response:

To improve on the other user's answer a bit, you can still use writerows like this.

import csv

keys = ["id", "name", "age", "height", "weight"]
 
with open('temp.csv', 'w') as temp_file:
    dict_writer_obj = csv.DictWriter(temp_file, fieldnames = keys) 

    with open('dictReader.csv','r') as file:
        dict_reader_obj = csv.DictReader(file) 
        dict_writer_obj.writeheader()
        # Here:
        dict_writer_obj.writerows(row for row in dict_reader_obj)

CodePudding user response:

Just change:

dict_writer_obj.writerows(file)

to:

dict_writer_obj.writerows(row for row in dict_reader_obj)

Or row by row using .writerow():

for row in dict_reader_obj:
    dict_writer_obj.writerow(row)
  • Related