如何在Python中将二进制文件读取为十六进制?

2024-05-15 16:13:09 发布

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

我想读取一个十六进制格式的数据文件:

01ff0aa121221aff110120...etc

这些文件包含100.000个这样的字节,有些超过了1000.000(它们来自DNA测序)

我尝试了以下代码(以及其他类似代码):

filele=1234563
f=open('data.geno','r')
c=[]
for i in range(filele):
  a=f.read(1)
  b=a.encode("hex")
  c.append(b)
f.close()

这给每个字节单独的“aa”“01”“f1”等,这对我来说是完美的!

在这种情况下,可以工作到恰好是“1a”的905字节。我还尝试了同样在同一字节停止的ord()函数。

也许有一个简单的解决办法?


Tags: 文件代码inforreaddata字节数据文件
3条回答

只需在这些文件中添加一个附加注释,请确保在您的.read文件中添加一个中断,否则它将继续运行。

def HexView():
    with open(<yourfilehere>, 'rb') as in_file:
        while True:
            hexdata = in_file.read(16).hex()     # I like to read 16 bytes in then new line it.
            if len(hexdata) == 0:                # breaks loop once no more binary data is read
                break
            print(hexdata.upper())               # I also like it all in caps. 

如果文件是以十六进制格式编码的,难道每个字节不应该用两个字符表示吗?所以

c=[]
with open('data.geno','rb') as f:
    b = f.read(2)
    while b:
        c.append(b.decode('hex'))
        b=f.read(2)

简单的解决方案是^{}

import binascii

# Open in binary mode (so you don't read two byte line endings on Windows as one byte)
# and use with statement (always do this to avoid leaked file descriptors, unflushed files)
with open('data.geno', 'rb') as f:
    # Slurp the whole file and efficiently convert it to hex all at once
    hexdata = binascii.hexlify(f.read())

这只会得到十六进制值的str,但它的速度比您尝试的要快得多。如果您真的需要一组长度为每个字节2个十六进制字符串,您可以很容易地转换结果:

hexlist = map(''.join, zip(hexdata[::2], hexdata[1::2]))

它将生成与每个字节的十六进制编码相对应的len 2strs的列表。为了避免hexdata的临时副本,可以使用类似但稍不直观的方法,通过使用同一个迭代器两次使用zip来避免切片:

hexlist = map(''.join, zip(*[iter(hexdata)]*2))

更新:

对于Python 3.5及更高版本的用户,^{} objects spawned a ^{} method,因此不需要模块将原始二进制数据转换为ASCII hex。顶部的代码块可以简化为:

with open('data.geno', 'rb') as f:
    hexdata = f.read().hex()

相关问题 更多 >