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

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

问题描述

import hashlib

infile = open(P:\\r.mp3,'r + b' )
data = infile.readline()
hash = hashlib.md5()
hash.update(data)
$ b $ hash_digest = hash.hexdigest()
print(hash_digest)
#hash_digest = hash_digest.encode('utf-8')
print(hash_digest)
with open(lt.txt,'ab')as outfile :
outfile.write(hash_digest +'\\\
')#error here

with open(syncDB.txt,'rb')as fg:
for data in fg:
print(data)



  outfile.write(hash_digest +'\ n')
TypeError:'str'不支持缓冲区接口

我怎样才能改正这个问题,并且我需要学习如何通过这些情况来了解我?

这在UTF-8(取消注释)它给出了以下错误:

  TypeError:无法将字节转换为str 


解决方案您正在使用Python 3,其中文本( str )和数据(>字节)。

有两种方法可以做到这一点:



1)以文本模式打开文件(可能使用指定的编码),以便为您自动编码字符串:

  with open(lt.txt,'at',encoding ='utf8')as outfile:
outfile.write(hash_digest +'\\\
') #或print(hash_digest,file = outfile)

如果在打开时没有指定编码文本模式下的文件将使用系统语言环境的默认编码。

<2>像您尝试的那样手动编码字符串。但是不要像你所做的那样,将 str 字节混合使用,或者使用字节字面量:



$ prefid =lang-python prettyprint-override> hash_digest = hash_digest.encode('utf-8')
with open(lt.txt ,'ab')as outfile:
outfile.write(hash_digest + b'\\\
')#注意b代表字节

或在添加换行符后进行编码:

  outfile .write((hash_digest +'\\\
')。encode('utf-8'))


import hashlib

infile = open("P:\\r.mp3", 'r+b')
data = infile.readline()
hash = hashlib.md5()
hash.update(data)

hash_digest = hash.hexdigest()
print(hash_digest)
#hash_digest = hash_digest.encode('utf-8')
print(hash_digest)
with open("lt.txt", 'ab') as outfile:
    outfile.write(hash_digest + '\n')   #error here

with open("syncDB.txt", 'rb') as fg:
    for data in fg:
    print(data)

outfile.write(hash_digest + '\n')
TypeError: 'str' does not support the buffer interface

How do I correct that and what do I need to learn to see me through these situations?

Also if I encode this in utf-8(uncomment) it gives out the following error:

TypeError: can't concat bytes to str

解决方案

You're using Python 3, where there is a strict division between text (str) and data (bytes). Text can't be written to a file if you don't explicitly encode it first.

There are two ways to do this:

1) Open the file in text mode (possibly with an encoding specified) so that strings are automatically encoded for you:

with open("lt.txt", 'at', encoding='utf8') as outfile:
    outfile.write(hash_digest + '\n') # or print(hash_digest, file=outfile)

If you don't specify the encoding yourself when opening the file in text mode, the default encoding of your system locale would be used.

2) Encode the strings manually like you tried. But don't try to mix str with bytes like you did, either use a byte literal:

hash_digest = hash_digest.encode('utf-8')
with open("lt.txt", 'ab') as outfile:
    outfile.write(hash_digest + b'\n')   # note the b for bytes

or encode after adding the newline:

    outfile.write((hash_digest + '\n').encode('utf-8'))

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

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