十六进制转储文件的pythonic方法 [英] pythonic way to hex dump files
问题描述
我的问题很简单:
有什么方法可以通过bash命令的pythonic方式进行编码吗?
Is there any way to code in a pythonic way that bash command?
hexdump -e '2/1 "%02x"' file.dat
很明显,没有使用os,popen或任何快捷方式;)
Obviously, without using os, popen, or any shortcut ;)
尽管我没有明确指定,但是如果代码在Python3.x中可以正常工作,那就太好了
although I've not explicitly specified, it would be great if the code was functional in Python3.x
谢谢!
推荐答案
If you only care about Python 2.x, line.encode('hex')
will encode a chunk of binary data into hex. So:
with open('file.dat', 'rb') as f:
for chunk in iter(lambda: f.read(32), b''):
print chunk.encode('hex')
(默认情况下,IIRC,hexdump
每行打印32对十六进制;如果没有,只需将32
更改为16
或其他内容……)
(IIRC, hexdump
by default prints 32 pairs of hex per line; if not, just change that 32
to 16
or whatever it is…)
如果两个参数 iter
看起来莫名其妙,请单击帮助链接;一旦您有了主意,它就不会太复杂.
如果您关心Python 3.x,请 encode
仅适用于将Unicode字符串转换为字节的编解码器;任何以其他方式转换的编解码器(或任何其他组合),则必须使用
If you care about Python 3.x, encode
only works for codecs that convert Unicode strings to bytes; any codecs that convert the other way around (or any other combination), you have to use codecs.encode
to do it explicitly:
with open('file.dat', 'rb') as f:
for chunk in iter(lambda: f.read(32), b''):
print(codecs.encode(chunk, 'hex'))
或者最好使用 hexlify
:
Or it may be better to use hexlify
:
with open('file.dat', 'rb') as f:
for chunk in iter(lambda: f.read(32), b''):
print(binascii.hexlify(chunk))
如果您除了打印输出外还想做些其他事情,而不是将整个文件读入内存,您可能想要创建一个迭代器.您可以将其放在函数中,然后将print
更改为yield
,该函数将恰好返回您想要的迭代器.或使用genexpr或map
呼叫:
If you want to do something besides print them out, rather than read the whole file into memory, you probably want to make an iterator. You could just put this in a function and change that print
to a yield
, and that function returns exactly the iterator you want. Or use a genexpr or map
call:
with open('file.dat', 'rb') as f:
chunks = iter(lambda: f.read(32), b'')
hexlines = map(binascii.hexlify, chunks)
这篇关于十六进制转储文件的pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!