有没有一种简单的方法,在Python中,将文件的十六进制数据读入列表,比如说hex?
那hex就是这样的:
hex = ['AA','CD','FF','0F']
我不想读成一个字符串,然后拆分.这对于大文件来说是内存密集型的.
cri*_*007 10
s = "Hello"
hex_list = ["{:02x}".format(ord(c)) for c in s]
Run Code Online (Sandbox Code Playgroud)
产量
['48', '65', '6c', '6c', '6f']
Run Code Online (Sandbox Code Playgroud)
只要换s到open(filename).read(),你就应该好.
with open('/path/to/some/file', 'r') as fp:
hex_list = ["{:02x}".format(ord(c)) for c in fp.read()]
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想将整个列表一次性保存在内存中以用于大文件.
hex_list = ("{:02x}".format(ord(c)) for c in fp.read())
Run Code Online (Sandbox Code Playgroud)
并获得价值,继续打电话
next(hex_list)
Run Code Online (Sandbox Code Playgroud)
从生成器获取所有剩余值
list(hex_list)
Run Code Online (Sandbox Code Playgroud)
使用 Python 3,假设输入文件包含您显示的示例字节。例如,我们可以像这样创建它
>>> inp = bytes((170,12*16+13,255,15)) # i.e. b'\xaa\xcd\xff\x0f'
>>> with open(filename,'wb') as f:
... f.write(inp)
Run Code Online (Sandbox Code Playgroud)
现在,假设我们想要输入文件中每个字节的十六进制表示,最好以二进制模式打开文件,而不必尝试将其内容解释为字符/字符串(否则我们可能会出错UnicodeDecodeError: 'utf-8' codec can't decode byte 0xaa in position 0: invalid start byte)
>>> with open(filename,'rb') as f:
... buff = f.read() # it reads the whole file into memory
...
>>> buff
b'\xaa\xcd\xff\x0f'
>>> out_hex = ['{:02X}'.format(b) for b in buff]
>>> out_hex
['AA', 'CD', 'FF', '0F']
Run Code Online (Sandbox Code Playgroud)
如果文件很大,我们可能希望一次或分块读取一个字符。为此,我建议阅读此问答