Python:以十六进制查看所有文件

0 投票
3 回答
3842 浏览
提问于 2025-04-15 23:04

我正在写一个Python脚本,目的是查看一些常见的计算机文件,并检查它们里面是否有相似的字节、单词和双字(就是两个字节)。不过,我想以十六进制的形式查看这些文件,但我似乎无法让Python简单地打开一个文件。我尝试过用codecs.open来以十六进制编码打开文件,但每次我对文件进行操作时,它总是返回

      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()

我其实只是想查看这些文件,并像在xxd这样的十六进制编辑器中那样对它们进行操作。另外,能不能一次读取文件中的一个字(就是四个字节)呢?

不,这不是作业。

3 个回答

1

如果这样说会更清楚的话... :

这是一个叫做 `hexfile` 的函数,里面有一个参数 `file_path`,它代表文件的路径。比如说,文件路径可能是 "C:/somedir/filename.ext"。

在这个函数里,首先用 `open` 打开这个文件,然后进入一个无限循环。在循环里,每次读取文件中的4个字节的数据。如果读取到的数据为空,就跳出循环。最后,把读取到的数据转换成十六进制格式并打印出来。

顺便说一下,这个方法挺不错的,应该能很好地满足我的需求。:)

1

你可以通过给 read 函数传递一个整数,来读取固定数量的字节:

32bits = file.read(4)

你可以使用 seek 函数在文件中移动到某个位置:

file.seek(100) # Seeks to byte 100
4

codecs.open(_file, "rb", "hex") 是在尝试把文件的内容解码为十六进制格式,这就是它出错的原因。

考虑到你提到的“每次一个字”的目标(我猜你是指“计算机字”,也就是32位?),你最好把打开的文件封装到你自己的一个类里面。例如:

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')

当然,你还可以添加其他你觉得有用的工具方法。

撰写回答