尝试运行以下内容时出现错误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
的数据类型,但我不确定我做错了什么。
答案 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格式包含一些标题,而不仅仅是像素数据,因此在修改后它可能会损坏。