pythonic方式到十六进制转储文件

pel*_*zza 4 python hexdump

我的问题很简单:

有没有办法用pythonic方式编码bash命令?

hexdump -e '2/1 "%02x"' file.dat
Run Code Online (Sandbox Code Playgroud)

显然,不使用os,popen或任何捷径;)

编辑:虽然我没有明确指定,但如果代码在Python3.x中有效,那将会很棒

谢谢!

aba*_*ert 11

如果您只关心Python 2.x,line.encode('hex')则会将一大块二进制数据编码为十六进制.所以:

with open('file.dat', 'rb') as f:
    for chunk in iter(lambda: f.read(32), b''):
        print chunk.encode('hex')
Run Code Online (Sandbox Code Playgroud)

(IIRC,hexdump默认情况下每行打印32对十六进制;如果没有,只需将其更改3216或者不管它是什么......)

如果两个参数iter看起来莫名其妙,请单击帮助链接; 一旦你明白了,它就不会太复杂了.

如果你关心Python 3.x,encode只适用于将Unicode字符串转换为字节的编解码器; 任何转换相反方式的编解码器(或任何其他组合),您必须使用codecs.encode显式执行:

with open('file.dat', 'rb') as f:
    for chunk in iter(lambda: f.read(32), b''):
        print(codecs.encode(chunk, 'hex'))
Run Code Online (Sandbox Code Playgroud)

或者使用它可能更好hexlify:

with open('file.dat', 'rb') as f:
    for chunk in iter(lambda: f.read(32), b''):
        print(binascii.hexlify(chunk))
Run Code Online (Sandbox Code Playgroud)

如果你想做除了打印之外的事情,而不是将整个文件读入内存,你可能想要创建一个迭代器.您可以将它放在一个函数中并将其更改print为a yield,该函数将返回您想要的迭代器.或者使用genexpr或map致电:

with open('file.dat', 'rb') as f:
    chunks = iter(lambda: f.read(32), b'')
    hexlines = map(binascii.hexlify, chunks)
Run Code Online (Sandbox Code Playgroud)


Ray*_*ger 9

标准库是你的朋友.试试binascii.hexlify().


kay*_*kay 6

只需read()整个文件和encode('hex').什么可能更pythonic?

with open('file.dat', 'rb') as f:
    hex_content = f.read().encode('hex')
Run Code Online (Sandbox Code Playgroud)

  • 很好的方法,它有效,但仅适用于 python2。这是 Py3.4 中的输出:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xac in position 0: invalid start byte (2认同)