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

标签 python python-2.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 又名 \r\n 变为 \n 又名 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> 。至少你从一开始就做不到!

关于python - 在 python 中读取文件时意外中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40952298/

相关文章:

python - 如何查看 CPython 文档何时发生更改/增强

android - 从 android 调用 Python 谷歌云端点 api

python-2.7 - 如何使用广播从具有列表 2d 索引的 2D numpy 数组中获取元素?

PYTHONPATH冲突

python - 使用模式重命名文件

python - 从目录中读取 pandas 中的多个文件 csv 并将它们存储在列表数组中,每个文件作为一个观察

python - 使用 Python str.splitlines() 处理尾随换行符

python - 如何在没有高级集合的情况下删除某个字母的所有出现? (Python)

Python Google App Engine Cron 作业/计划任务不工作

python 2.7 : "can' t start new thread"error from "multiprocessing.Pool"