python加压解压zip,rar文件

压缩文件,解压文件是常遇到的事情。如何处理呢?

class Unrar_or_unzip:
    """This Class can extrac zipfile or rarfile."""
    def __init__(self, file):
        """The arguement of file can be a file name or a file path + file name"""
        self.basename = os.path.basename(file)
        self.basedir = os.path.dirname(file)

    def unrar_or_unzip(self):
        """return file type(zip or rar),file basedir, file basename"""
        if ".rar" in self.basename:
            return ["rarfile", self.basedir, self.basename]
            Unrar_or_unzip(file).un_rar(self.basedir, self.basename)
        elif ".zip" in self.basename:
            return ["zipfile", self.basedir, self.basename]

    def un_rar(self, path, file):
        """Extract rar file!
        Argue path is the dir, file is the one which will be extract!"""
        try:
            if path != "":
                os.chdir("/")
                os.chdir(path)
            rar = rarfile.RarFile(file)
            os.mkdir(file[:-4]) #创建rar文件解压后的存放路径
            rar.extractall(file[:-4]) #解压文件到指定路径
            print("Un_rar file[%s] Successfully!" % file)
        except Exception as e:
            print("Un_rar file[%s] failed!" % file)
            print("Error:", str(e))
        finally:
            rar.close()

    def un_zip(self, path, file):
        """Extract rar file!
        Argue path is the dir, file is the one which will be extract!"""
        try:
            if path != "":
                os.chdir("/")
                os.chdir(path)
            zip_package = zipfile.ZipFile(file)
            os.mkdir(file[:-4]) #创建rar文件解压后的存放路径
            zip_package.extractall(file[:-4]) #解压文件到指定路径
            print("Un_ZIP file[%s] Successfully!" % file)
        except Exception as e:
            print("Un_ZIP file[%s] failed!" % file)
            print("Error:", str(e))
        finally:
            zip_package.close()

以上类的作用是:判断该压缩包是zip类型还是rar类型,根据不同类型选择不同的解压方式。

class Compress_to_zip:
    def __init__(self, filename):
            self.zipfile = zipfile.ZipFile(filename, "a", zipfile.ZIP_DEFLATED)

    def compress_to_zip(self, dirname):
        try:
            for dirpath, dirnames, filenames in os.walk(dirname):
                for filename in filenames:
                    self.zipfile.write(os.path.join(dirpath,filename))
            print("Compress To Zipfile Successfully!")
        except Exception as e:
            print("Compress Files[%s] Error:%s", (dirname, str(e)))

    def add_to_zip(self, filename, dirpath="", arcname=""):
        """压缩文件filename 至zipfile文件内,
        dirpath 为压缩文件至zip文件内的某一目录(需要注意的是:1.dirpath 内必须要有文件filename
        2.dirpath与arcname不能兼容 --- 方法研究中。。。)
         arcname 为压缩至文件内的文件名称,"""
        try:
            if not arcname:
                arcname = filenamenn
            if not dirpath:
                self.zipfile.write(filename, arcname)
            else:
                self.zipfile.write(os.path.join(dirpath,filename))
            print("Added File Compress To Zipfile Successfully!")
        except Exception as e:
            print("Compress file[%s] to zipfile Error:%s", (filename, str(e)))

    def disconnect(self):
        self.zipfile.close()

以上是解压zip文件包的代码。
要注意一点的是 :调用compress_to_zip方法时传入的目录如果是绝对路径的话,那么压缩包内压缩的文件filename内的文件是以绝对路径的形式压缩进去的。

你可能感兴趣的:(python学习)