2016-04-22 47 views
1

我有一個包含整數和雙精度的二進制文件。我想通過一次調用(類似於:x = np.fromfile(f, dtype=np.int))或按順序(按值計算)來訪問這些數據。但是,NumPy似乎不允許在不指定類型的情況下從二進制文件讀取數據。我應該將所有東西都轉換成雙倍,還是忘記了NumPy?從Python/NumPy中包含整數和雙精度的二進制文件讀取或構建數組

編輯。比方說,文件的格式是這樣的:

INT

INT INT INT雙雙雙雙雙雙雙

+1

檢查出來的'struct'模塊。 – roadrunner66

+0

爲什麼你不能讀取值的值,假設你知道文件的格式,從而知道哪個是整數,哪個是double,然後用提升的類型填充numpy數組(例如所有浮點數)? – Cyb3rFly3r

+1

「我有一個包含整數和雙精度的二進制文件」 - 這個二進制文件的格式是什麼? 「二進制文件」不足以說明這些數據是如何表示的;沒有更多的信息,我們無法告訴如何閱讀這個文件。 – user2357112

回答

0
NumPy doesn't seem to allow to read from a binary file without specifying a type 

無需編程語言,我知道的假裝能夠猜測原始二進制數據的類型;並有充分的理由。你試圖解決的高層次問題究竟是什麼?

0

我不認爲你需要這個numpy。基本的Python二進制庫struct正在完成這項工作。如果需要的話,將在末尾給出的元組列表轉換爲numpy數組。

對於源看到https://docs.python.org/2/library/struct.html和@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 

輸出:

(1, 2, 3, 1.100000023841858, 0.02199999988079071, 0.0032999999821186066, 0.0004400000034365803, 5.500000042957254e-05, 6.599999778700294e-06, 7.699999855503847e-07) 

顯示在一個二進制編輯器將二進制文件(Frhed):

enter image description here

#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 

輸出:

[(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)] 
相關問題