简体   繁体   中英

Creating dictionary file using a csv file in python

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

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM