写入字节到文件时出现“TypeError:'list'不支持缓冲区接口”错误

4

当我尝试运行以下代码时,出现错误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个回答

4
读取文件后,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格式包含一些头文件,不仅仅是像素数据,因此在这样的修改后,它可能会变得损坏。

谢谢!我知道报头的存在(前14个字节是元数据),我计划在实现主要的负载-修改-保存系统后进行修改。 - Dakeyras
经过一些测试,如果我将一个“整数”转换为“字节”对象,则可以工作,但是如果我尝试将“二进制”转换为“字节”,则无法工作。 - Dakeyras

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接