Advertisement
Fhernd

leer-escribir-arreglos-binarios.py

Aug 3rd, 2018
2,889
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.64 KB | None | 0 0
  1. from struct import Struct
  2.  
  3. def escribir_datos(datos, formato, f):
  4.     estructura = Struct(formato)
  5.  
  6.     for dato in datos:
  7.         f.write(estructura.pack(*dato))
  8.  
  9. def leer_datos(formato, f):
  10.     estructura = Struct(formato)
  11.  
  12.     partes = iter(lambda: f.read(estructura.size), b'')
  13.  
  14.     return (estructura.unpack(parte) for parte in partes)
  15.  
  16. # Punto de entrada:
  17. if __name__ == '__main__':
  18.     datos = [(2, 3, 5), (7, 11, 13), (17, 19, 23)]
  19.  
  20.     with open('datos.bin', 'wb') as f:
  21.         escribir_datos(datos, '<idd', f)
  22.  
  23.     with open('datos.bin', 'rb') as f:
  24.         for dato in leer_datos('<idd', f):
  25.             print(dato)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement