【问题标题】:python détect if file is tar or tar.gz or zippython 检测文件是否为 tar 或 tar.gz 或 zip
【发布时间】:2017-12-16 22:19:23
【问题描述】:

我有一个问题,我需要识别文件类型(tar、tar.gz 或 zip)我在这个站点找到了一个解决方案: Python - mechanism to identify compressed file type and uncompress

但该解决方案不适用于 tar 文件,因为 tar 文件的起始字符不同...

magic_dict = {
    "\x1f\x8b\x08": "gz",
    "\x00\x00\x00": "tar",
    "\x50\x4b\x03\x04": "zip"
    }

max_len = max(len(x) for x in magic_dict)

def file_type(filename):
    with open(filename) as f:
        file_start = f.read(max_len)
    for magic, filetype in magic_dict.items():
        if file_start.startswith(magic):
            return filetype
    return "no match"

如何检测 tar 文件?

【问题讨论】:

  • 这是python 2还是python 3?
  • 我使用 python 2.7

标签: python compression tar


【解决方案1】:

至少 GNU tar 一个“魔术签名”,但它不是在偏移量 0(文件的开头),而是在偏移量 257,它是字符串 ustar 后跟NUL 字符;见https://en.wikipedia.org/wiki/Tar_(computing)#UStar_format

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 2014-04-10
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 2018-12-26
    相关资源
    最近更新 更多