十六进制转储文件的pythonic方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25005505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pythonic way to hex dump files
提问by peluzza
my question is simple:
我的问题很简单:
Is there any way to code in a pythonic way that bash command?
有没有办法以 bash 命令的pythonic方式进行编码?
hexdump -e '2/1 "%02x"' file.dat
Obviously, without using os, popen, or any shortcut ;)
显然,不使用 os、popen 或任何快捷方式;)
EDIT: although I've not explicitly specified, it would be great if the code was functional in Python3.x
编辑:虽然我没有明确指定,但如果代码在 Python3.x 中运行,那就太好了
Thanks!
谢谢!
采纳答案by abarnert
If you only care about Python 2.x, line.encode('hex')will encode a chunk of binary data into hex. So:
如果您只关心 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')
(IIRC, hexdumpby default prints 32 pairs of hex per line; if not, just change that 32to 16or whatever it is…)
(IIRC,hexdump默认情况下每行打印 32 对十六进制;如果没有,只需将其更改32为16或其他任何内容......)
If the two-argument iterlooks baffling, click the help link; it's not too complicated once you get the idea.
如果两个参数iter看起来莫名其妙,请单击帮助链接;一旦你有了想法,它并不太复杂。
If you care about Python 3.x, encodeonly 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.encodeto do it explicitly:
如果您关心 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'))
Or it may be better to use hexlify:
或者最好使用hexlify:
with open('file.dat', 'rb') as f:
for chunk in iter(lambda: f.read(32), b''):
print(binascii.hexlify(chunk))
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 printto a yield, and that function returns exactly the iterator you want. Or use a genexpr or mapcall:
如果你想在打印之外做一些事情,而不是将整个文件读入内存,你可能想要制作一个迭代器。您可以将它放在一个函数中并将其更改print为 a yield,该函数将准确返回您想要的迭代器。或者使用geneexpr或map调用:
with open('file.dat', 'rb') as f:
chunks = iter(lambda: f.read(32), b'')
hexlines = map(binascii.hexlify, chunks)
回答by kay - SE is evil
Simply read()the whole file and encode('hex'). What could be more pythonic?
只需read()整个文件和encode('hex'). 什么可以更pythonic?
with open('file.dat', 'rb') as f:
hex_content = f.read().encode('hex')
回答by Raymond Hettinger
The standard library is your friend. Try binascii.hexlify().
标准库是你的朋友。尝试binascii.hexlify()。

