如何在Python中读取32位浮点、64位浮点和其他32位浮点的二进制文件

2024-09-30 01:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个结构非常简单的二进制文件,用于学习。每个寄存器有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 0940 0800 0000  .....-DT.!.@....

(…)

如果我手动复制二进制格式的第三行,我可以将其读入三个变量:

^{pr2}$

这是可行的,但我需要从磁盘读取文件,不仅要手动以二进制形式复制每个寄存器,因为我需要使用数百万个数据来执行此操作。我需要与ascii文件中使用的以下命令等效的命令:

l1, value, l2 = pylab.loadtxt('./test_file.binary',unpack=True)

这在这里行不通。在


Tags: 文件命令屏幕格式dt二进制数字手动
2条回答

以二进制模式读取文件:

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)

这是发电机。要消耗它:

^{pr2}$

你可以试试这个方法

# 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!

相关问题 更多 >

    热门问题