0

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?

2
  • On which line are you encountering the error? Commented Apr 15, 2019 at 15:28
  • 2
    Open in w mode, not wb mode. The old bug for blank lines between rows in Windows is now fixed in Python 3 by adding newline='' instead of opening in wb mode. Commented Apr 15, 2019 at 15:28

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

No problem Happy to help :)
1

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.

1 Comment

Using the DictWriter from the csv module is better practice than doing it this way. What if the strings in the dictionary contain commas? You wouldn't write a valid, or at least correct, CSV file from this

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.