Domanda

I get the error TypeError: 'list' does not support the buffer interface when trying to run the following:

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()

Why is this happening? I think it is due to the data type I am writing to the .bmp but I am not sure what I am doing wrong.

È stato utile?

Soluzione

After you've read the file, data is a bytes object, which can behave like a list of numbers, but isn't one, while new is an actual list of numbers. Binary files support writing only bytes, so that's what you need to give it.

One solution is to replace file.write(new) with file.write(bytes(new)).

And here is a shorter rewrite of the code:

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)

Note that the BMP format contains some headers, not just pixel data, so it will probably become corrupt after such modification.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top