Python - 识别压缩文件类型和解压缩的机制

kum*_*ran 25 python compression zip rar tar

压缩文件可以分为以下逻辑组
a.您正在处理的操作系统(*ix,Win)等
.不同类型的压缩算法(即.zip,.Z,.bz2,.rar,.gzip).至少来自大多数使用压缩文件的标准列表.
C.然后我们有tar球机制 - 我认为没有压缩.但它更像是连接.

现在,如果我们开始解决上面的压缩文件集,
a.选项(a)将由python处理,因为它是与平台无关的语言.
湾 选项(b)和(c)似乎有问题.

我需要什么
如何识别文件类型(压缩类型)然后对它们进行UN压缩?


喜欢:

fileType = getFileType(fileName)  
switch(fileType):  
case .rar:  unrar....
case .zip:  unzip....

etc  
Run Code Online (Sandbox Code Playgroud)

所以基本问题是我们如何根据文件识别压缩算法(假设没有提供扩展或不正确)?在python中有没有特定的方法呢?

Lau*_*low 31

此页面包含"魔术"文件签名列表.抓住你需要的那些并将它们放入如下的字典中.然后我们需要一个将dict键与文件开头匹配的函数.我写了一个建议,虽然它可以通过预处理magic_dict到例如一个巨大的编译正则表达式进行优化.

magic_dict = {
    "\x1f\x8b\x08": "gz",
    "\x42\x5a\x68": "bz2",
    "\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"
Run Code Online (Sandbox Code Playgroud)

这个解决方案应该是跨平台的,当然不依赖于文件扩展名,但它可能会给具有随机内容的文件带来误报,这些内容恰好以某些特定的魔术字节开头.


Ber*_*Ber 14

基于lazyr的回答和我的评论,这就是我的意思:

class CompressedFile (object):
    magic = None
    file_type = None
    mime_type = None
    proper_extension = None

    def __init__(self, f):
        # f is an open file or file like object
        self.f = f
        self.accessor = self.open()

    @classmethod
    def is_magic(self, data):
        return data.startswith(self.magic)

    def open(self):
        return None

import zipfile

class ZIPFile (CompressedFile):
    magic = '\x50\x4b\x03\x04'
    file_type = 'zip'
    mime_type = 'compressed/zip'

    def open(self):
        return zipfile.ZipFile(self.f)

import bz2

class BZ2File (CompressedFile):
    magic = '\x42\x5a\x68'
    file_type = 'bz2'
    mime_type = 'compressed/bz2'

    def open(self):
        return bz2.BZ2File(self.f)

import gzip

class GZFile (CompressedFile):
    magic = '\x1f\x8b\x08'
    file_type = 'gz'
    mime_type = 'compressed/gz'

    def open(self):
        return gzip.GzipFile(self.f)


# factory function to create a suitable instance for accessing files
def get_compressed_file(filename):
    with file(filename, 'rb') as f:
        start_of_file = f.read(1024)
        f.seek(0)
        for cls in (ZIPFile, BZ2File, GZFile):
            if cls.is_magic(start_of_file):
                return cls(f)

        return None

filename='test.zip'
cf = get_compressed_file(filename)
if cf is not None:
    print filename, 'is a', cf.mime_type, 'file'
    print cf.accessor
Run Code Online (Sandbox Code Playgroud)

现在可以使用访问压缩数据了cf.accessor.所有模块都提供类似的方法,如'read()','write()'等.