【发布时间】:2021-12-02 06:50:44
【问题描述】:
通过输入带有扩展名的文件,我的代码成功地从“幻数”中检测到文件的类型。
magic_numbers = {'png': bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]),
'jpg': bytes([0xFF, 0xD8, 0xFF, 0xE0]),
#*********************#
'doc': bytes([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]),
'xls': bytes([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]),
'ppt': bytes([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]),
#*********************#
'docx': bytes([0x50, 0x4B, 0x03, 0x04, 0x14, 0x00, 0x06, 0x00]),
'xlsx': bytes([0x50, 0x4B, 0x03, 0x04, 0x14, 0x00, 0x06, 0x00]),
'pptx': bytes([0x50, 0x4B, 0x03, 0x04, 0x14, 0x00, 0x06, 0x00]),
#*********************#
'pdf': bytes([0x25, 0x50, 0x44, 0x46]),
#*********************#
'dll': bytes([0x4D, 0x5A, 0x90, 0x00]),
'exe': bytes([0x4D, 0x5A]),
}
max_read_size = max(len(m) for m in magic_numbers.values())
with open('file.pdf', 'rb') as fd:
file_head = fd.read(max_read_size)
if file_head.startswith(magic_numbers['pdf']):
print("It's a PDF File")
else:
print("It's not a PDF file")
我想知道如何在不指定这部分代码的情况下修改它,即一旦我生成或输入文件,它就会直接向我显示文件的类型。
if file_head.startswith(magic_numbers['pdf']):
print("It's a PDF File")
else:
print("It's not a PDF file")
希望你能理解我。
【问题讨论】:
-
那么,您想检查前几个字节而不读取前几个字节?
-
感谢您的回答,我想从我输入的“幻数”列表中读取内容并从该列表中检测文件类型。没有指定“如果是 PDF,你给我看 PDF”
-
是的,因此您需要遍历所有元素并测试每个元素。 for 循环为您提供每个键
-
老实说,我不知道该怎么做。
标签: python header-files detection file-type magic-numbers