162:ファイルを16進ダンプする
binascii.hexlify
binascii モジュールの hexlify 関数はバイナリデータを 16 進ダンプする関数です。
>>> import binascii
>>> binascii.hexlify('Python')
'507974686f6e'
これを用いるとファイルを 16 進ダンプする関数・スクリプトを作成することができます。たとえば、次のようになります。
# coding: utf-8
import sys
import binascii
def hexdump(in_file=sys.stdin, out_file=sys.stdout, bufsize=8192):
u"""ファイルを 16 進ダンプする"""
read = in_file.read
write = out_file.write
hexlify = binascii.hexlify
if hasattr(in_file, 'isatty') and in_file.isatty():
write(hexlify(read()))
else:
d = read(bufsize)
while d:
write(hexlify(d))
d = read(bufsize)
def main():
import optparse
usage = '%prog inputfile [...]'
option_parser = optparse.OptionParser(usage=usage)
options, args = option_parser.parse_args()
len_args = len(args)
if len_args == 0:
hexdump(sys.stdin, sys.stdout)
elif len_args == 1:
hexdump(open(args[0], 'rb'), sys.stdout)
else:
for arg in args:
sys.stdout.write(u'---------- %s ----------\n' % arg)
try:
f = open(arg, 'rb')
try:
hexdump(f, sys.stdout)
finally:
f.close()
except IOError, e:
sys.stdout.write(str(e))
sys.stdout.write(u'\n')
if __name__ == '__main__':
main()
$ python hexdump.py -h Usage: hexdump.py inputfile [...] Options: -h, --help show this help message and exit $ python hexdump.py python.txt 507974686f6e $ python hexdump.py python.txt ruby.txt ---------- python.txt ---------- 507974686f6e ---------- ruby.txt ---------- 52756279
binascii.unhexlify
16 進表記のテキストから元に戻す関数も存在します。 unhexlify 関数です。
>>> import binascii
>>> binascii.unhexlify('507974686f6e')
'Python'