1. python 解压zip压缩包或rar压缩包
import zipfile
# from unrar import rarfile # python2
import rarfile # python3
def zip_decompress(file_path, new_path):
"""支持中文的解压缩程序
file_path:原压缩包文件路径
new_path:新文件夹路径
"""
if file_path.split('.')[-1] == 'zip':
z = zipfile.ZipFile(file_path, 'r')
z.extractall(path=new_path)
else:
z = rarfile.RarFile(file_path, 'r')
z.extractall(path=new_path)
if __name__ == "__main__":
file_path = r"C:\test\zip_test\Django.rar"
new_path = r"C:\test\zip_test"
zip_decompress(file_path, new_path)
2. python将文件/文件夹压缩为zip压缩包
import os
import zipfile
def zipDir(dirpath, target_path):
"""
压缩指定文件夹
:param dirpath: 目标文件夹路径
:param target_path: 压缩文件保存路径
"""
pre_len = len(os.path.dirname(target_path))
zip = zipfile.ZipFile(target_path, "w", zipfile.ZIP_DEFLATED)
for path, dirnames, filenames in os.walk(dirpath):
# # 1.去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
# fpath = path.replace(dirpath, '')
# for filename in filenames:
# pathfile = os.path.join(path, filename)
# arcname = os.path.join(fpath, filename) # 归档文件
# zip.write(pathfile, arcname)
# 2. 带文件夹压缩
for filename in filenames:
pathfile = os.path.join(path, filename)
arcname = pathfile[pre_len:].strip(os.path.sep) # 相对路径
zip.write(pathfile, arcname)
zip.close()
if __name__ == "__main__":
dirpath = r"C:\test\zip_test\pdfconver"
target_path = r"C:\test\zip_test\pdfconver.zip"
zipDir(dirpath, target_path)