【问题标题】:Unexpected break while reading a file in python在 python 中读取文件时意外中断
【发布时间】:2016-12-03 20:43:14
【问题描述】:

我正在尝试在 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()

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

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

    虽然它在 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>。至少你不能从一开始就做到!

    【讨论】:

    • 非常感谢!我实际上是在read-call 之后直接关闭文件,我只是忘了在这里输入代码行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 2019-06-12
    • 2012-04-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    相关资源
    最近更新 更多