文件未正确解码

2024-09-29 23:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用奇怪的模式编码的文件。例如

字符(1字节)|整数(4字节)|双精度(8字节)|等…

到目前为止,我写了下面的代码,但我还没有弄清楚为什么仍然在屏幕上显示垃圾。任何帮助都将不胜感激。你知道吗

BRK_File = 'commands.BRK'
input = open(BRK_File, "rb")

rev = input.read(1)
filesize = input.read(4)
highpoint = input.read(8)
which = input.read(1)

print 'Revision: ', rev 
print 'File size: ', filesize
print 'High point: ', highpoint
print 'Which: ', which

while True
    opcode = input.read(1)
    print 'Opcode: ', opcode
    if opcode = 120:
         break
    elif
        #other opcodes

Tags: 文件编码whichreadinput字节模式rev
2条回答

显示文件的内容以及输出的“垃圾”会很有帮助。你知道吗

你知道吗输入.读取()返回一个字符串,因此必须将正在读取的内容转换为所需的类型。我建议研究一下struct模块。你知道吗

read()返回一个字符串,您需要对其进行解码以获得二进制数据。您可以使用^{}模块来进行解码。你知道吗

以下几点应该可以做到:

import struct
...
fmt = 'cid' # char, int, double
data = input.read(struct.calcsize(fmt))
rev, filesize, highpoint = struct.unpack(fmt, data)

您可能需要处理endianness问题,但是struct会导致pretty easy。你知道吗

相关问题 更多 >

    热门问题