python zip 压缩指定文件夹并解压到指定文件夹@dc
import os
import zipfile
def zip_dir(dir_path, zipfile_path):
"""
zip dir
:param dir_path: where zip dir path
:param zipfile_path: zip dir
:return:
"""
file_list = []
if os.path.isfile(dir_path):
file_list.append(dir_path)
else:
for root, dirs, files in os.walk(dir_path):
for name in files:
file_list.append(os.path.join(root, name))
zf = zipfile.ZipFile(zipfile_path, "w", zipfile.zlib.DEFLATED)
for file_path in file_list:
_dir = file_path[len(dir_path) - 1:]
zf.write(file_path, _dir)
zf.close()
def unzip_dir(file_path, file_paths):
zf = zipfile.ZipFile(file_path, 'r')
for file in zf.namelist():
zf.extract(file, file_paths)
import os
import glob
import zipfile
def unzip_file(dir_path):
# 解压缩后文件的存放路径
unzip_file_path = r"C:\Users\Desktop\新建文件夹"
# 找到压缩文件夹
dir_list = glob.glob(dir_path)
if dir_list:
# 循环zip文件夹
for dir_zip in dir_list:
# 以读的方式打开
with zipfile.ZipFile(dir_zip, 'r') as f:
for file in f.namelist():
f.extract(file, path=unzip_file_path)
os.remove(dir_zip)
unzip_file(r"C:\Users\Desktop\新建文件夹\*.zip")
# 这儿的 dir_path 只是其中的一种路径处理方式,可以根据自己的需求行进实际操作
import os
import zipfile
def zip_dir(dir_path, zip_path):
'''
:param dir_path: 目标文件夹路径
:param zip_path: 压缩后的文件夹路径
:return:
'''
zip = zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED)
for root, dirnames, filenames in os.walk(dir_path):
file_path = root.replace(dir_path, '') # 去掉根路径,只对目标文件夹下的文件及文件夹进行压缩
# 循环出一个个文件名
for filename in filenames:
zip.write(os.path.join(root, filename), os.path.join(file_path, filename))
zip.close()
zip_dir(r"C:\Users\Desktop\新建文件夹", r"C:\Users\Desktop\压缩" + '.zip')
if __name__ == '__main__':
if not os.path.exists("/tmp/a/b"):
os.makedirs("/tmp/a/b")
os.mknod("/tmp/a.txt")
os.rename("/tmp/a.txt", "/tmp/a/b/c.sq3")
zip_dir('/tmp/a', "/tmp/e.zip")
unzip_dir("/tmp/e.zip", "/tmp")