首页 > 解决方案 > 读取块中的bin文件并找出python中的特定值

问题描述

以下代码无法在 bin 文件中查找特定值,与其他代码相比,它需要更长的时间。

with open(fileName, mode='rb') as f:
    x = os.stat(fileName).st_size
    y = int(x/4)
    print('x,y:', x, y)
    for i in range(0, y, 4):
        x = st.unpack('<I', f.read(4))
        if x == int("00000050", 16):
            print("loc:")

但是下面的代码正在工作。我很好奇我在上面的代码中做错了什么?

        with open(filename, mode='rb') as f:
            b = f.read()
            np_data = np.frombuffer(b, dtype=np.uint16)
            findIndex = np.where(np_data == int("00000050", 16))

提前致谢!!

标签: pythonpython-3.x

解决方案


我在您的第一个代码片段中看到了几个“危险点”。1.) 在第 2 行定义x = os.stat(fileName).st_size,在第 5 行重新定义x = st.unpack('<I', f.read(4))。虽然这可能不是非法的或导致编译器问题,但由于 x 在 while 循环的范围内,因此重新分配这样的变量并不是一个好习惯,而且它至少会导致以后理解您的代码时出现问题。

2.) 您一次读取 4 个字节的文件,我想这比第二个代码片段中采用的方法要慢得多,后者读取整个文件。

3.)在你的第一个代码片段的最后一行,你print("loc:")和你可能想要做类似的事情print("loc:", x)

  1. 使用 numpy 库查找索引比循环遍历更快,因为 numpy 已针对该类型的搜索进行了优化。

为了至少使您的第一个片段工作,您可以尝试:

with open(fileName, mode='rb') as f:
    x = os.stat(fileName).st_size
    y = int(x/4)
    print('x,y:', x, y)
    ptr = 0
    while True:
        itm = f.read(4)
        if itm == b'':
            break
        ptr += 4
        if st.unpack('<I', itm) == int("00000050", 16):
            print("loc:", ptr)

推荐阅读