Skip to main content
 首页 » 编程设计

python之在 python 中读取文件时意外中断

2024年10月17日7三少

我正在尝试在 python 2.7 中为 cmd 编写一个十六进制查看器
它几乎可以正常工作,但是如果我尝试在 Windows 上查看已编译的文件,它只会显示其中的一小部分。我已经发现,read() 在第一次出现 0x1a(ASCII 格式)时中断。 Notepad++ 将此字符显示为 SUB。我不知道这个控制字符的作用,为什么 read() 停在这个字符上,以及如何避免这个中断。谁能帮帮我?

这是我的全部代码:

    def main(): 
 
        while True: 
            print "Enter a file path:" 
            path = raw_input() 
            f = open(path, 'r') 
            text = f.read() # seems to break at 0x1a/SUB 
            f.close() 
            for c in text: 
                hex_c = hex(ord(c))[2:] 
                if len(hex_c) % 2: # if the hex number consists of 1 digit 
                    hex_c = '0' + hex_c # fill the string with a zero 
                print hex_c, 
            print # just as a line break in the console 
 
    if __name__ == '__main__': 
 
        main() 

请您参考如下方法:

f = open(path, 'r')以文本模式打开文件。

虽然它在 Linux 上并不重要,但如果您仍然使用 Python 2.x,在 Windows 上,文本模式启用行尾转换(CRLF 变成 LF aka \r\n 变成 \n aka 0x0D 0x0A 变成 0x0A )

我必须承认我无法解释为什么您有这种行为,但是对于十六进制编辑器,您以二进制方式打开文件,否则您将丢失所有 0x0d字节(以及我显然没有意识到的其他惊喜,我会做更多的研究):

f = open(path, 'rb') 

不执行任何转换,以原始模式访问文件,我看不出它不能解决您的问题。

(也不要忘记 f.close() 您的文件,因为它目前尚未完成,或者使用 with open(path,"rb") as f: 语句。

顺便说一句:直接的 2 位十六进制可以通过以下方式实现:hex_c = "%02x" % ord(c)

编辑:我尝试使用 python 3,它甚至不允许我将二进制文件作为文本读取。我得到了 UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 46: character maps to <undefined> .至少你不能从一开始就这样做!