2017-03-31 161 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。 –