在python中写入二进制文件
我想用python将一些东西写入二进制文件 我只是在做:在python中写入二进制文件,python,numpy,binary,Python,Numpy,Binary,我想用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) secon
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,I,'int32');”中很容易做到这一点,但我想在python中做到这一点。这是因为您试图将字符串(编辑)写入二进制文件。在再次尝试读取之前,您也不会关闭该文件。
如果要将整数或字符串写入二进制文件,请尝试添加以下代码:
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
您似乎对Python中的类型有些困惑 表达式
'i'+'j'
将两个字符串相加。这将导致字符串ij
,它很可能以两个字节的形式写入文件
变量i
已经是int
。您可以通过几种不同的方式将其作为4字节整数写入文件(这也适用于浮点j
):
struct
模块,如中所述。大概是这样的:
import struct
with open('binary.file', 'wb') as f:
f.write(struct.pack("i", i))
您可以使用'd'
说明符来编写j
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)
请注意,在这两种情况下,当使用
with
块编写文件时,我都使用open
作为上下文管理器。这样可以确保即使在写入过程中发生错误,也会关闭文件。您不会将4和5.55写入文件。您可以写入105(ASCII代码为'i'
)和106(ASCII代码为'j'
)。行f.write('i'+'j')
将字符串'ij'
写入文件。您需要使用,以便将数据正确编码为二进制。由于您使用numpy.fromfile
加载数据,最自然的做法是使用numpy.ndarray.tofile
存储数据。(但请注意,建议使用numpy.save
和numpy.load
来代替。)nump.save将数据保存到.npy文件。在本例中,是否最好使用带有open('binary.file','wb')的作为f:
语法来建立更好的实践?当然,它解决了关闭文件的问题。我试图让它尽可能接近原始代码。编辑:添加了open…我要么成对使用Numpy的tofile
和fromfile
,要么使用struct
模块进行读写。此外,他没有向文件写入总和,而是将'ij'
作为字符串写入。另外,我不确定这是否是重复的,例如,你是对的,大卫,我错过了他在vars周围的比赛。那j
呢?