-1
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'}
4
  • Did you mean "dictionary based file" as originally written , or perhaps a Python "dictionary object" that can be used in code? Commented Oct 29, 2021 at 15:43
  • 1
    What is what you really want to do, your code is just reading from one csv and trying to write to the other one Commented Oct 29, 2021 at 15:49
  • 1
    "dictionary based file", do you mean a JSON-file? Please show us an example of what you want the output to look like, to compliment your description. Commented Oct 29, 2021 at 15:51
  • 1
    Does this answer your question? Convert CSV to JSON file in python Commented Oct 29, 2021 at 15:57

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.