fred.schwartz
fred.schwartz

Reputation: 2155

Saving dictionary to csv python

Hi When I try and save a dictionary to a csv using the following code:

with open(file, 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, my_dictionary.keys())
    w.writeheader()
    w.writerow(my_dictionary)

I get this error message

TypeError: a bytes-like object is required, not 'str'

Is there a fix for this?

Upvotes: 0

Views: 82

Answers (2)

SeF
SeF

Reputation: 4188

I think this is not the best practice. If your goal is only to get the dictionary in csv, then you can store the dictionary line by line with keys and values separated in the way you prefer,

with open('/home/sebastiano/Desktop/test.txt', 'w+') as f: 
         for k, v in d.items(): 
             f.write('{}, {}'.format(k, v)) 

Otherwise, you should use the library pickle, so you will be able to reload exactly as same object.

Upvotes: 1

You opened the file in binary mode hence the b you need to just get rid of that and put w and I think it should work. When a file is opened in binary mode it means that all the data read from a file is returned as bytes not of type 'str'. Thus if you wanted to keep the b there you would need to use bytes for everything else

Upvotes: 2

Related Questions