1. import os
    2. import tarfile
    3. import zipfile
    4. def uncompress(src_file, dest_dir):
    5. """解压各种类型的压缩包
    6. :param src_file: 你要解压的压缩包文件
    7. :type src_file: file
    8. :param dest_dir: 你要解压到的目标路径
    9. :type dest_dir: str
    10. """
    11. file_name, file_type = os.path.splitext(src_file.name)
    12. try:
    13. if file_type == '.zip':
    14. # 需要安装zip包:pip install zipp
    15. zip_file = zipfile.ZipFile(src_file)
    16. for names in zip_file.namelist():
    17. zip_file.extract(names, dest_dir)
    18. zip_file.close()
    19. elif file_type == '.rar':
    20. # 需要安装rar包:pip install rarfile
    21. rar = rarfile.RarFile(src_file)
    22. os.chdir(dest_dir)
    23. rar.extractall()
    24. rar.close()
    25. else:
    26. # file_type == '.tgz' or file_type == '.tar' or file_type == '.gz'
    27. # Python自带tarfile模块
    28. tar = tarfile.open(fileobj=src_file)
    29. for name in tar.getnames():
    30. tar.extract(name, dest_dir)
    31. tar.close()
    32. except Exception as ex:
    33. return False
    34. return True
    35. if __name__ == '__main__':
    36. dest_dir = '你要解压到的目标路径'
    37. with open('你要解压的压缩包文件路径', 'rb') as src_file:
    38. result = uncompress(src_file, dest_dir)