python - 读取块中的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))
提前致谢!!
解决方案
我在您的第一个代码片段中看到了几个“危险点”。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)
- 使用 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)
推荐阅读
- unity3d - 如何使用统一和增强现实在人的皮肤上蚀刻像纹身一样的图像?
- angular - Angular 6-Activated Route-为什么我无法从路由中提取 ID?
- javascript - How to unparse result after iterating through specific data with papaparse?
- tensorflow - 诗人的 TensorFlow - 运行重新训练脚本时出错(Windows 10)
- c# - C#比较字符串和缩写
- mercurial - 如何从 hg 日志中获取分支名称?
- php - SimpleSAMLphp 设置和 SP 元数据
- javascript - 在 axios 获取请求中未定义的反应状态
- keras - 如何将我自己的数据集转换为 x_train y _train , x_test x_train
- php - Wordpress REST Api 请求适用于直接调用,但不适用于脚本