Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created August 4, 2018 14:23
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/496f566d770c358429518182fb55321e to your computer and use it in GitHub Desktop.
Save Fhernd/496f566d770c358429518182fb55321e to your computer and use it in GitHub Desktop.
Escritura y lectura de estructuras de datos anidadas en formato binario. OrtizOL.
import struct
import itertools
def escribir_polilineas(archivo, polilineas):
lista_plana = list(itertools.chain(*polilineas))
min_x = min(x for x, y in lista_plana)
max_x = max(x for x, y in lista_plana)
min_y = min(y for x, y in lista_plana)
max_y = max(y for x, y in lista_plana)
with open(archivo, 'wb') as f:
f.write(struct.pack('<iddddi',
0x1234,
min_x, min_y,
max_x, max_y,
len(polilineas)))
for polilinea in polilineas:
tamahnio = len(polilinea) * struct.calcsize('<dd')
f.write(struct.pack('<i', tamahnio + 4))
for punto in polilinea:
f.write(struct.pack('<dd', *punto))
def leer_polilineas(archivo):
with open(archivo, 'rb') as f:
encabezado = f.read(40)
codigo, min_x, min_y, max_x, max_y, numero_polilineas = struct.unpack('<iddddi', encabezado)
polilineas = []
for n in range(numero_polilineas):
bytes_punto, = struct.unpack('<i', f.read(4))
polilinea = []
for m in range(bytes_punto // 16):
punto = struct.unpack('<dd', f.read(16))
polilinea.append(punto)
polilineas.append(polilinea)
return polilineas
polilineas = [
[(1.0, 2.5), (3.5, 4.0), (2.5, 1.5)],
[(7.0, 1.2), (5.1, 3.0), (0.5, 7.5), (0.8, 9.0)],
[(3.4, 6.3), (1.2, 0.5), (4.6, 9.2)]
]
escribir_polilineas('polilineas.bin', polilineas)
print(leer_polilineas('polilineas.bin'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment