Python TypeError:'str'不支持缓冲区接口 [英] Python TypeError: 'str' does not support the buffer interface

查看:293
本文介绍了Python TypeError:'str'不支持缓冲区接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码,工作正常,然后开始抛出这个错误。我有一个csv文件,我想写一行。虽然其他解决方案涉及将事物转换为字节字符串,因为我使用csv,我不知道我可以这样做。



代码:

  def saveFile():
with open('data.csv','wb' )as out:
csv_out = csv.writer(out)
csv_out.writerow(['Domain:','Mail Server:','TLS:','#of Employees:','Verified :'])
对于root.pt.get_rows()中的行:
#csv_out.writerow(row)
print(row)
/ pre>

错误:

 回溯(最近调用最后):
文件C:\Python34\lib\tkinter\__init __。py,第1487行,在__call__
中return self.func(* args)
文件C:/Users/kylec/Desktop/DataMotion/Python/MailChecker.py,第93行,位于saveFile
csv_out.writerow(['Domain:','Mail Server:','TLS :','#of Employees:','Verified:'])
TypeError:'str'不支持缓冲区接口


解决方案

在Python 3中, csv 模块希望你在 ('data.csv','w',newline ='')的文字模式::

 as out:

newline =''参数给出了 csv 模块控制如何写入换行符(在Python 2中以二进制模式打开文件的原因)。



csv.writer( )文档


如果 csvfile 应该用 newline =''打开。



[...]



如果未指定 newline ='',则嵌入在引用字段中的新行不会被正确解释,在使用 \r\\\
linendings写入额外的 \r 将被添加。指定 newline =''应该是安全的,因为csv模块有自己的(通用)换行处理。


因为你给模块一个二进制模式文件,你只能写 bytes data


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

解决方案

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.

这篇关于Python TypeError:'str'不支持缓冲区接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆