0

I have the below code that was working fine and then started throwing this error. I have a csv file that I am trying to write one row to. While other solutions involve converting things to a byte string first, since I'm working with a csv, I'm not sure I can do that.

Code:

def saveFile():
    with open('data.csv','wb') as out:
        csv_out=csv.writer(out)
        csv_out.writerow(['Domain:','Mail Server:','TLS:','# of Employees:','Verified:'])
        for row in root.pt.get_rows():
            #csv_out.writerow(row)
            print (row)

Error:

Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
    return self.func(*args)
  File "C:/Users/kylec/Desktop/DataMotion/Python/MailChecker.py", line 93, in saveFile
    csv_out.writerow(['Domain:','Mail Server:','TLS:','# of Employees:','Verified:'])
TypeError: 'str' does not support the buffer interface

1 Answer 1

3

In Python 3, the csv module expects you to give it a file in text mode:

with open('data.csv', 'w', newline='') as out:

The newline='' argument gives the csv module control over how newlines are written (the reason why in Python 2 you opened the file in binary mode).

From the csv.writer() documentation:

If csvfile is a file object, it should be opened with newline=''.

[...]

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

Because you gave the module a binary-mode file, you can only write bytes data to it.

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

2 Comments

Just so I know, isn't that what wb is for?
@Kyle: in Python 2 you'd have to open the file in binary mode, yes. But this isn't Python 2.

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.