简体   繁体   English

在python中使用csv文件创建字典文件

[英]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.我想将名为 dictReader.csv 文件的 csv 文件转换为基于字典的文件:但是我收到以下错误。 Any ideas?有任何想法吗? AttributeError: 'str' object has no attribute 'keys' AttributeError: 'str' 对象没有属性 'keys'

My dictReader.csv file content:我的 dictReader.csv 文件内容:

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具有此格式的名为 temp.csv 的所需输出文件


{'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.为了稍微改进其他用户的答案,您仍然可以使用这样的writerows

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() :或者使用.writerow()

for row in dict_reader_obj:
    dict_writer_obj.writerow(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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