Python:查看Hex中的所有文件 [英] Python: Seeing all files in Hex

查看:1014
本文介绍了Python:查看Hex中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个python脚本,它查看常见的计算机文件并检查它们是否有类似的字节,单词,双字。虽然我需要/希望以十六进制格式查看文件,但ande实际上并不能让python在python中打开一个简单的文件。我曾尝试codecs.open与十六进制作为编码,但是当我在文件描述符上操作时,它总是回吐

I am writing a python script which looks at common computer files and examines them for similar bytes, words, double word's. Though I need/want to see the files in Hex, ande cannot really seem to get python to open a simple file in python. I have tried codecs.open with hex as the encoding, but when I operate on the file descriptor it always spits back

      File "main.py", line 41, in <module>
    main()
  File "main.py", line 38, in main
    process_file(sys.argv[1])
  File "main.py", line 27, in process_file
    seeker(line.rstrip("\n"))
  File "main.py", line 15, in seeker
    for unit in f.read(2):
  File "/usr/lib/python2.6/codecs.py", line 666, in read
    return self.reader.read(size)
  File "/usr/lib/python2.6/codecs.py", line 472, in read
    newchars, decodedbytes = self.decode(data, self.errors)
  File "/usr/lib/python2.6/encodings/hex_codec.py", line 50, in decode
    return hex_decode(input,errors)
  File "/usr/lib/python2.6/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found





def seeker(_file):
 f = codecs.open(_file, "rb", "hex")
 for LINE in f.read():
      print LINE
 f.close()

我真的只想看文件,而ope就像它在xxd等十六进制编辑器中一样。也可以一次读取一个文件,也许一次增加一个词。

I really just want to see files, and operate on them as if it was in a hex editor like xxd. Also is it possible to read a file in increments of maybe a word at a time.

不是这不是家庭作业。

推荐答案

codecs.open(_file,rb,hex)正在尝试解码文件内容为十六进制,这就是为什么它会失败。

codecs.open(_file, "rb", "hex") is trying to decode the file's contents as being hex, which is why it's failing on you.

考虑到你的其他一次一个字的目标(我假设你的意思是计算机字,即32位?),你最好把打开的文件封装到你自己的类中。例如:

Considering your other "word at a time" target (I assume you mean "computer word", i.e. 32 bits?), you'll be better off encapsulating the open file into a class of your own. E.g.:

class HexFile(object):
    def __init__(self, fp, wordsize=4):
        self.fp = fp
        self.ws = wordsize
    def __iter__(self):
        while True:
            data = self.fp.read(self.ws)
            if not data: break
            yield data.encode('hex')

加上其他任何你会发现有用的实用方法。

plus whatever other utility methods you'd find helpful, of course.

这篇关于Python:查看Hex中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆