如何创建定义的结构化元数据以使用?

时间:2020-02-18 11:11:17

标签: python metadata

我开始学习python并尝试读取具有定义结构的日志文件

12 34 20 02 02 14 15 10 03 02 03 0A 00 02 60 17 0A 80 0B 00 01 72 0B 80 0C 00 01 45 0C 80
56 78 20 02 02 14 15 10

数据可以解码为:

12 34                   --> First file number (2 bytes)
20 02 02 14 15 10       --> file written date (6 bytes)
03 02                   --> File Id
03                      --> No of files

0A 00   --> sub file number 1 start
02      --> length of the file
20 07   --> data in the file
0A 80   --> sub file number 1 end

0B 00   --> sub file number 2 start
01      --> length of the file
72      --> data in the file
0B 80   --> sub file number 2 end

0C 00   --> sub file number 3 start
01      --> length of the file
45      --> data in the file
0C 80   --> sub file number 3 end


56 78               --> Second file number (2 bytes)
20 02 02 14 15 10   --> file written date (6 bytes)
.......
........
...

基于“文件数”值= 3,接下来的3个部分应为3个数据块,其起始,长度,文件内部的数据和结束值。

在此部分之后,具有相同结构数据的另一部分将再次可用。

我尝试逐字节读取,但是认为可以正确定义并且是初学者,尝试更多地学习python。

# First file number
byte = file.read(2)
hexadecimal = binascii.hexlify(byte)
print("First File number      : %s" %(codecs.decode(hexadecimal, "hex").decode('ascii')))

# code for date

# First file Id
byte = file.read(2)
hexadecimal = binascii.hexlify(byte)
print("First File Id      : %s" %(codecs.decode(hexadecimal, "hex").decode('ascii')))

如何用更好的方式写出来?另外,如果我将此逻辑写在另一个文件中,则通过将文件作为输入参数传递,所有详细信息都应在元组或dict中获取?

1 个答案:

答案 0 :(得分:1)

查看标准库中的struct模块。它提供了一个名为unpack的功能。

struct.unpack(format, buffer)

根据格式字符串格式从缓冲区缓冲区(可能由pack(format, ...)打包)中解压缩。结果是一个元组,即使它只包含一个项目。缓冲区的大小(以字节为单位)必须与格式要求的大小匹配,如calcsize()所反映。

重要的是文件的字节序/字节顺序。在我的文章中,我假设您的文件始终为小端。

Character  | Byte order | Size     | Alignment
@            native       native     native
=            native       standard   none
<            little       standard   none
>            big          standard   none

此表告诉您所需的格式名称。这是<。 您可以在https://docs.python.org/3/library/struct.html#format-characters查看类型的格式代码。 第一个结构,文件头,首先由一个16位无符号整数,然后是6个字节的数据,一个16位无符号整数,然后是一个无符号字节组成。因此,文件标头的格式代码为'<H6sBHB'。因此,读取文件标题可能如下所示:

from struct import unpack
header = f.read(11)
file_number, date, file_id, file_count = unpack('<H6sHB', header)

使用struct.iter_unpack,您现在可以解析所有子文件头。

subfile_headers = f.read(7 * file_count)  # One subfile header takes 7 bytes
subfile_iterator = struct.iter_unpack('<HBHH', subfile_headers)
for start, length, data, end in subfile_iterator:
    ...  # do something with the subfile headers

我希望这会有所帮助,尽管我没有完全理解您的问题。 如果您可以提供一些有关此文件的信息,这将很有帮助。 如果您能向我解释部分问题,我也可能会为您提供更多帮助:

另外,如果我将此逻辑写在另一个文件中,则通过将文件作为输入参数传递,所有详细信息都应以元组或dict的形式获取?

相关问题