如何在Python中读取具有32位浮点、64位浮点和另一个32位浮点的二进制文件
这是一个二进制文件,结构非常简单,便于学习。每个寄存器有3个数字:32位浮点、64位浮点和另一个32位浮点。如果以十六进制格式将其转储到屏幕上,则如下所示:如何在Python中读取具有32位浮点、64位浮点和另一个32位浮点的二进制文件,python,binaryfiles,Python,Binaryfiles,这是一个二进制文件,结构非常简单,便于学习。每个寄存器有3个数字:32位浮点、64位浮点和另一个32位浮点。如果以十六进制格式将其转储到屏幕上,则如下所示: 0000000: 0800 0000 0000 0000 0000 0000 0800 0000 ................ 0000010: 0800 0000 0000 0000 0000 f03f 0800 0000 ...........?.... 0000020: 0800 0000 182d 4454 fb21 094
0000000: 0800 0000 0000 0000 0000 0000 0800 0000 ................
0000010: 0800 0000 0000 0000 0000 f03f 0800 0000 ...........?....
0000020: 0800 0000 182d 4454 fb21 0940 0800 0000 .....-DT.!.@....
(……)
如果我手动复制二进制格式的第三行,我可以将其读入三个变量:
import struct
data = b'\x08\x00\x00\x00\x18-DT\xfb!\t@\x08\x00\x00\x00'
l1, value, l2 = struct.unpack("<idi", data)
# (8, 3.141592653589793, 8)
在这里不起作用。以二进制模式读取文件:
def read_stuff(fname='test_file.binary'):
with open(fname, mode='rb') as f:
while True:
data = f.read(16)
if len(data) < 16:
# end of file
return
yield struct.unpack("<idi", data)
你可以试试这个方法
# includes core parts of numpy, matplotlib
import matplotlib.pyplot as plt
import numpy as np
# include scipy's signal processing functions
import scipy.signal as signal
# practice reading in complex values stored in a file
# Read in data that has been stored as raw I/Q interleaved 32-bit float samples
dat = np.fromfile("iqsamples.float32", dtype="float32")
# Look at the data. Is it complex?
dat = dat[0::2] + 1j*dat[1::2]
print(type(dat))
print(dat)
# # Plot the spectogram of this data
plt.specgram(dat, NFFT=1024, Fs=1000000)
plt.title("PSD of 'signal' loaded from file")
plt.xlabel("Time")
plt.ylabel("Frequency")
plt.show() # if you've done this right, you should see a fun surprise here!
这是整个文件还是文件中有更多数据?如果这三个变量的值超过了这个值,那么您希望从这三个变量中得到什么?每个文件有几百万个寄存器(或行,或者您如何命名)。在这一条语句中缺少
If
?@BillBell修复,谢谢。请随时直接编辑next time.def read_stuff(fname='test_file.binary')语法错误:语法无效,它指向右括号。隐秘的python错误消息。两小时后对着屏幕大喊大叫。它应该很简单。
for l1, value, l2 in read_stuff():
...
# includes core parts of numpy, matplotlib
import matplotlib.pyplot as plt
import numpy as np
# include scipy's signal processing functions
import scipy.signal as signal
# practice reading in complex values stored in a file
# Read in data that has been stored as raw I/Q interleaved 32-bit float samples
dat = np.fromfile("iqsamples.float32", dtype="float32")
# Look at the data. Is it complex?
dat = dat[0::2] + 1j*dat[1::2]
print(type(dat))
print(dat)
# # Plot the spectogram of this data
plt.specgram(dat, NFFT=1024, Fs=1000000)
plt.title("PSD of 'signal' loaded from file")
plt.xlabel("Time")
plt.ylabel("Frequency")
plt.show() # if you've done this right, you should see a fun surprise here!