TypeError:'str'不支持缓冲区接口

10 投票
2 回答
22583 浏览
提问于 2025-04-17 00:03
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

我该如何纠正这个问题?我需要学习什么才能应对这些情况?

另外,如果我把这个编码成utf-8(取消注释),会出现以下错误:

TypeError: can't concat bytes to str

2 个回答

-5

你需要在谷歌上搜索'str' 不支持缓冲区接口

你会找到很多类似这样的答案:

stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface

至于第二个错误 **TypeError: 不能将字节与字符串连接**,我觉得你应该在 f.write(hex + '\n') 中写成 b'\n'

""" 编辑

没错,Rosh Oxymoron 说得对,应该是 b'\n',而不是 u'\n'。

23

你正在使用Python 3,在这个版本中,文本(str)和数据(bytes)是严格分开的。如果你不先把文本编码,无法直接把它写入文件。

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

1) 以文本模式打开文件(可以指定编码),这样字符串会自动为你编码:

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

如果你在以文本模式打开文件时没有自己指定编码,系统会使用你电脑的默认编码。

2) 像你之前尝试的那样手动编码字符串。但不要把strbytes混在一起使用,你可以使用字节字面量:

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

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

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

撰写回答