4

I am trying to save output from a module to CSV file and I got an error when I ran the following code, which is a part of a module:

base_keys = ['path', 'rDATE', 'cDate', 'cik', 'risk', 'word_count']
outFile = open('c:\\Users\\ahn_133\\Desktop\\Python Project\\MinkAhn_completed2.csv','wb')
dWriter = csv.DictWriter(outFile, fieldnames=base_keys)
dWriter.writerow(headerDict)

Here is the error message (base_keys are the headings.)

return self.writer.writerow(self._dict_to_list(rowdict))
TypeError: 'str' does not support the buffer interface

I dont' even understand what the error message is about. I use Python 3.3 and Windows 7.

Thanks for your time.

4
  • Show more of your code, especially the definition of _dict_to_list. Commented Dec 9, 2012 at 17:48
  • Python3 uses bytes instead of strings in many cases where encoding comes into play. Try encoding/decoding where appropriate. Commented Dec 9, 2012 at 17:49
  • @NedBatchelder It’s library code Commented Dec 9, 2012 at 17:53
  • 2
    Then I'll give you the First Rule of Debugging: When In Doubt, Print More Out. What value is _dict_to_list returning? If it's well-named, it's a list, but maybe it isn't. Commented Dec 9, 2012 at 18:04

1 Answer 1

6

Opening a file in binary mode to write csv data to doesn't work in Python 3, simply put. What you want is to open in text mode and either use the default encoding or specify one yourself, i.e., your code should be written like:

import csv
k = ['hi']
out = open('bleh.csv', 'w', newline='', encoding='utf8') # mode could be 'wt' for extra-clarity
writer = csv.DictWriter(out, k)
writer.writerow({'hi': 'hey'})

Now, due to a bug, you also need to specify newline='' when opening this file for writing the CSV output.

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

4 Comments

the bug was about code examples for csv.writer in csv docs lacking newline='' in Python 3. The bug is not the cause.
I'm not following you @J.F.Sebastian, are you implying that newline='' doesn't affect Python 3, or that it doesn't affect when using csv.DicWriter, or something else ? This certainly wasn't the problem in OP's code because he couldn't even write to the file (because he opened in binary mode), but it would be the next bug.
look at the patch that fixes the bug. It is a documentation bug, no code in cvs is changed due to this bug. Your answer implies that there is some bug in csv module itself (the code).
I've seen it. While my answer never said it was a bug in the code (and only that it was a bug) we can get into this new argument. But I'm not seeing the importance of discussing 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.