Transfer list to Python binary file

Asked

Viewed 278 times

0

Good morning programmers. Need to put a list in a binary file but is showing error.

 lista = [-1, 333.0, -1, 333.0, 10, 8.0, 45, -66.5999984741211, 12, -44.70000076293945]

Code:

  open("saida.bin", "wb") as arq1:
  for x in lista:
      arq1.write(struct.pack('=i', x))
      arq1.write(struct.pack('=f', x))
  arq1.close()

error:

arq1.write(struct.pack('=i', x))
struct.error: required argument is not an integer

1 answer

1


The error tells you exactly what the problem is. When you do

arq1.write(struct.pack('=i', x))

Is trying to get x in a space int (as indicated by =i), that is, an integer. A careful observation of the list reveals that some of the values are not integers (333.0, -66.59, etc.).

You are also adding the same values as float, that is, floating point numbers (not integers) on the line below that.

As a float may assume an integer value but a int cannot assume a fractional value, what I would recommend is simply removing the line

arq1.write(struct.pack('=i', x))

So your numbers will be saved as float and you can return them to a list normally:

with open('saida.bin', 'rb') as f:
    print(struct.unpack('=10f', f.read()))
# (-1.0, 333.0, -1.0, 333.0, 10.0, 8.0, 45.0, -66.5999984741211, 12.0, -44.70000076293945)

If you need to keep the integer number format for your application, then you will have to check the type of the variable before inserting it into the struct.

with open("saida.bin", "wb") as arq1:
    for x in lista:
        if isinstance(x, int):
            arq1.write(struct.pack('=i', x))
        elif isinstance(x, float):
            arq1.write(struct.pack('=f', x))
        else:
            raise TypeError('x não é int nem float!')

But then you have other problems to solve because you also have to know the type of variable to give unpack. Thus, either you must be sure that the items in the list have their types in a certain order, or store together some information about which element has which type, or you must store them separately.

  • Thanks peter for the answer, friend has how I make an interaction and exchange the values of this list in case it is integer put -1 and if it is float put 999.0 directly inside the binary file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.