2017-03-31 158 views
1

我想寫一些東西到使用Python的二進制文件。寫入二進制文件python

我只是做:

import numpy as np 

f = open('binary.file','wb') 
i=4 
j=5.55 
f.write('i'+'j') #where do i specify that i is an integer and j is a double? 

g = open('binary.file','rb') 
first = np.fromfile(g,dtype=np.uint32,count = 1) 
second = np.fromfile(g,dtype=np.float64,count = 1) 

print first, second 

輸出只是: [] []

我知道這是很容易做到這一點在Matlab「FWRITE(binary.file,我, 'int32');「,但我想在python中完成它。

+2

你不寫入4和5.55到文件中。你寫105(「i」的ASCII碼)和106(「j」的ASCII碼)。 – DyZ

+0

'f.write'('i'+'j')'行將字符串''ij''寫入文件。您將需要使用[struct.pack](https://docs.python.org/2.7/library/struct.html#struct.pack),以便將數據正確編碼爲二進制。 –

+0

既然您使用'numpy.fromfile'來加載數據,最自然的事情就是使用'numpy.ndarray.tofile'來存儲數據。 (但請注意[文檔](https://docs.scipy.org/doc/numpy/reference/generated/numpy。fromfile.html)推薦使用'numpy.save'和'numpy.load'代替。) –

回答

2

你似乎是具有約在Python類型一些混亂。

表達式'i' + 'j'將兩個字符串加在一起。這導致字符串ij,這很可能寫入文件爲兩個字節。

變量i已經是int。你可以把它寫入一個文件在幾個不同的方式(這也適用於浮動j)一個4字節的整數:

  1. 使用struct模塊中how to write integer number in particular no of bytes in python (file writing)詳述。事情是這樣的:

    import struct 
    with open('binary.file', 'wb') as f: 
        f.write(struct.pack("i", i)) 
    

    你會使用'd'符寫j

  2. 使用numpy模塊爲您寫文章,這是特別方便的,因爲您已經在使用它來讀取文件。該方法ndarray.tofile只是爲了這個目的做:

    i = 4 
    j = 5.55 
    with open('binary.file', 'wb') as f: 
        np.array(i, dtype=np.uint32).tofile(f) 
        np.array(j, dtype=np.float64).tofile(f) 
    

注意,在這兩種情況下,我使用open作爲上下文管理與with塊寫入文件時。這可確保文件關閉,即使在寫入期間發生錯誤。

-1

這是因爲您正在嘗試將字符串(編輯)寫入二進制文件。在嘗試再次讀取文件之前,您也不要關閉該文件。
如果你想要寫整數或字符串二進制文件嘗試添加下面的代碼:

import numpy as np 
import struct 

f = open('binary.file','wb') 
i = 4 
if isinstance(i, int): 
    f.write(struct.pack('i', i)) # write an int 
elif isinstance(i, str): 
    f.write(i) # write a string 
else: 
    raise TypeError('Can only write str or int') 

f.close() 

g = open('binary.file','rb') 
first = np.fromfile(g,dtype=np.uint32,count = 1) 
second = np.fromfile(g,dtype=np.float64,count = 1) 

print first, second  

我要把它留給你找出浮點數。

打印第一,第二
[4] []

的更Python文件處理程序的方法:

import numpy as np 
import struct 

with open ('binary.file','wb') as f: 
    i = 4 
    if isinstance(i, int): 
     f.write(struct.pack('i', i)) # write an int 
    elif isinstance(i, str): 
     f.write(i) # write a string 
    else: 
     raise TypeError('Can only write str or int') 

with open('binary.file','rb') as g: 
    first = np.fromfile(g,dtype=np.uint32,count = 1) 
    second = np.fromfile(g,dtype=np.float64,count = 1) 

print first, second  
+0

可能最好使用'with open('binary.file ','wb')作爲f:'在這個例子中的語法來建立更好的實踐? –

+0

當然,它解決了關閉文件的問題。我試圖儘可能地使其儘可能接近原始代碼。編輯:添加打開... – Artagel

+0

我會使用Numpy的'tofile'和'fromfile'成對,或'結構'模塊進行讀寫。另外,他並沒有給文件寫一筆金額,而是把字符串「ij」作爲一個字符串。 此外,我不確定這不是重複的http://stackoverflow.com/questions/37129257/python-writing-int-to-a-binary-file。 –