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

San*_*alp 10 python file-io md5

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)
Run Code Online (Sandbox Code Playgroud)
outfile.write(hash_digest + '\n')
TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)

我如何纠正这一点以及在这些情况下我需要学习什么才能看到我?

此外,如果我在utf-8(取消注释)中对此进行编码,则会发出以下错误:

TypeError: can't concat bytes to str
Run Code Online (Sandbox Code Playgroud)

Ros*_*ron 23

您正在使用Python 3,其中text(str)和data(bytes)之间存在严格的划分.如果您没有先对文本进行显式编码,则无法将文本写入文件.

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

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

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

如果在文本模式下打开文件时未自行指定编码,则将使用系统区域设置的默认编码.

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
Run Code Online (Sandbox Code Playgroud)

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

    outfile.write((hash_digest + '\n').encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

  • 如果你使用with-open-as,则不需要调用f.close().(当然我意识到你只是匹配OP的代码.) (3认同)