首页 > 解决方案 > 从特定字节读取二进制文件

问题描述

我正在尝试从特定字节(143)读取二进制文件,直到另一个特定字节(150)。

我正在运行这个命令:

tail -c +143 full_file.dat | head -c 6 | od -t x1
0000000 20 04 08 13 06 37
0000006

我有我想要的值(20 04 08 13 06)。

但是,使用 Python 尝试相同(至少我是这么想的),我得到了这个:

'\x04\x08\x13\x067+'

我在 Python 中运行的命令是:

g = open('full_file.DAT', 'rb')
g.seek(143, 1)
g.read(6)

我在这里做错了什么?

标签: python

解决方案


你可以使用 Numpy 做这样的事情:

import Numpy as np

arr = np.fromfile('full_file.DAT', dtype='uint8')
arr[143:143+6] #==> [20 04 08 13 06 37]

推荐阅读