python对文件夹或文件进行压缩

import os
import zipfile


# 压缩文件夹
def zip_ya(folder_name, zip_name):  # folder_name 要压缩的文件夹路径; zip_name压缩后文件夹的名字
    z = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
    for dirpath, dirnames, filenames in os.walk(folder_name):
        fpath = dirpath.replace(folder_name, '')  # 不使用replace会从根目录开始复制
        fpath = fpath and fpath + os.sep or ''  # 实现当前文件夹以及包含的所有文件的压缩
        for filename in filenames:
            z.write(os.path.join(dirpath, filename), fpath + filename)
    z.close()
    print("压缩完成!")


# 多文件压缩
def zip_files(files, zip_name):  # files=['./a.jpg', ./b.jpg]  可以把多个文件压缩成一个包
    zip = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
    for file in files:
        print('compressing', file)
        zip.write(file)
    zip.close()
    print('压缩完成!')

你可能感兴趣的:(python)