Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

string - Python TypeError: 'str' does not support the buffer interface

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:Python34libkinter\__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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 linendings on write an extra 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...