Python: Seeing all files in Hex

后端 未结 3 444
说谎
说谎 2021-01-28 11:10

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 c

相关标签:
3条回答
  • 2021-01-28 11:28

    You can read a set number of bytes by passing an integer argument to read:

    32bits = file.read(4)
    

    You can seek to a position in the file using seek:

    file.seek(100) # Seeks to byte 100
    
    0 讨论(0)
  • 2021-01-28 11:32

    if this will be more clear... : def hexfile(file_path): fp=open(file_path) while True: data = fp.read(4) if not data: break print data.encode('hex')

    file_path is something like "C:/somedir/filename.ext" it nice method btw it will work nicely for me. :)

    0 讨论(0)
  • 2021-01-28 11:33

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

    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.

    0 讨论(0)
提交回复
热议问题