Transfer list to binary file in python

0

Good morning programmers. I need to put a list in a binary file but it is displaying an 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
    
asked by anonymous 28.04.2018 / 13:36

1 answer

1

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

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

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

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

As a float can assume an integer value but a int can not assume a fractional value, what I would recommend is simply remove 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 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 the variable when giving unpack . So either you should make sure that the items in the list have their types in a certain order, or you can save some information about which element has which type, or you should store them separately.

    
28.04.2018 / 14:57