Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created August 3, 2018 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/0914aa69d50cc6f773116ce7ceddd50b to your computer and use it in GitHub Desktop.
Save Fhernd/0914aa69d50cc6f773116ce7ceddd50b to your computer and use it in GitHub Desktop.
Leer y escribir arreglos como datos binarios en Python. OrtizOL.
from struct import Struct
def escribir_datos(datos, formato, f):
estructura = Struct(formato)
for dato in datos:
f.write(estructura.pack(*dato))
def leer_datos(formato, f):
estructura = Struct(formato)
partes = iter(lambda: f.read(estructura.size), b'')
return (estructura.unpack(parte) for parte in partes)
# Punto de entrada:
if __name__ == '__main__':
datos = [(2, 3, 5), (7, 11, 13), (17, 19, 23)]
with open('datos.bin', 'wb') as f:
escribir_datos(datos, '<idd', f)
with open('datos.bin', 'rb') as f:
for dato in leer_datos('<idd', f):
print(dato)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment