将字节写入文件时,“TypeError:'list'不支持缓冲区接口”

时间:2013-06-13 16:39:01

标签: python python-3.x binary-data

尝试运行以下内容时出现错误TypeError: 'list' does not support the buffer interface

file = open(filename + ".bmp", "rb")
data = file.read()
file.close()
new = []

for byte in data:
    byte = int(byte)
    if byte%2:#make even numbers odd
        byte -= 1
    new.append(bin(byte))

file = open(filename + ".bmp", "wb")
file.write(new)
file.close()

为什么会这样?我认为这是由于我写给.bmp的数据类型,但我不确定我做错了什么。

1 个答案:

答案 0 :(得分:3)

在您阅读完文件后,data是一个bytes对象,其行为类似于数字列表,但不是一个,而new是一个实际列表数字。二进制文件只支持写入字节,因此您需要提供它。

一种解决方案是将file.write(new)替换为file.write(bytes(new))

以下是对代码的重写:

with open(filename+'.bmp', 'rb') as in_file:
    data = in_file.read()

new_data = bytes(byte//2*2 for byte in data)

with open(filename+'.bmp', 'wb') as out_file:
    out_file.write(new_data)

请注意,BMP格式包含一些标题,而不仅仅是像素数据,因此在修改后它可能会损坏。