Ich glaube nicht, dass Sie dafür brauchen würden. Die grundlegende Python-Binärbibliothek struct
macht die Arbeit. Konvertiere die Liste der am Ende gegebenen Tupel in ein numpliges Array, falls dies gewünscht wird.
Quellen siehe https://docs.python.org/2/library/struct.html und @martineau Reading a binary file into a struct in Python
from struct import pack,unpack
with open("foo.bin","wb") as file:
a=pack("<iiifffffff", 1,2,3, 1.1,2.2e-2,3.3e-3,4.4e-4,5.5e-5,6.6e-6,7.7e-7)
file.write(a)
with open("foo.bin","r") as file:
a=unpack("<iiifffffff",file.read())
print a
Ausgang:
(1, 2, 3, 1.100000023841858, 0.02199999988079071, 0.0032999999821186066, 0.0004400000034365803, 5.500000042957254e-05, 6.599999778700294e-06, 7.699999855503847e-07)
die binäre Datei in einem Binär-Editor angezeigt (Frhed):
#how to read same structure repeatedly
import struct
fn="foo2.bin"
struct_fmt = '<iiifffffff'
struct_len = struct.calcsize(struct_fmt)
struct_unpack = struct.Struct(struct_fmt).unpack_from
with open(fn,"wb") as file:
a=struct.pack("<iiifffffff", 1,2,3, 1.1,2.2e-2,3.3e-3,4.4e-4,5.5e-5,6.6e-6,7.7e-7)
for i in range(3):
file.write(a)
results = []
with open(fn, "rb") as f:
while True:
data = f.read(struct_len)
if not data: break
s = struct_unpack(data)
results.append(s)
print results
Ausgabe:
[(1, 2, 3, 1.100000023841858, 0.02199999988079071, 0.0032999999821186066, 0.0004400000034365803, 5.500000042957254e-05, 6.599999778700294e-06, 7.699999855503847e-07), (1, 2, 3, 1.100000023841858, 0.02199999988079071, 0.0032999999821186066, 0.0004400000034365803, 5.500000042957254e-05, 6.599999778700294e-06, 7.699999855503847e-07), (1, 2, 3, 1.100000023841858, 0.02199999988079071, 0.0032999999821186066, 0.0004400000034365803, 5.500000042957254e-05, 6.599999778700294e-06, 7.699999855503847e-07)]
Schauen Sie sich die 'struct' Modul. – roadrunner66
Warum können Sie value-by-value nicht lesen, vorausgesetzt, Sie kennen das Format der Datei und damit wissen, welche eine ganze Zahl ist und welche eine doppelte, füllen Sie dann die numpy Array mit dem beworbenen Typ (z. B. alle float)? – Cyb3rFly3r
"Ich habe eine Binärdatei, die sowohl Ganzzahlen als auch Doppel enthält" - welches Format hat diese Binärdatei? "Binärdatei" ist nicht genug Information, um zu sagen, wie diese Daten dargestellt werden; Ohne weitere Informationen können wir nicht sagen, wie diese Datei zu lesen ist. – user2357112