import os
import zipfile
# 压缩文件
def compress(target):
"""
target:待压缩的文件或者文件夹
"""
zip_name = os.path.basename(os.path.normpath(target)).split('.')[0] + '.zip'
zipFile = zipfile.ZipFile(os.path.join(os.path.dirname(target), zip_name), 'w', zipfile.ZIP_DEFLATED)
if not os.path.isdir(target):
print(target)
zipFile.write(filename=target, arcname=os.path.relpath(target, os.path.dirname(target)))
else:
for folder_name, sub_folders, files in os.walk(target):
for item in files:
file = os.path.join(folder_name, item)
print(file)
zipFile.write(file, arcname=os.path.relpath(file, os.path.dirname(target)))
zipFile.close()
if __name__ == '__main__':
value = r'C:\Users\ZhouMO\Desktop\截图'
compress(value)
Python使用zipfile模块对指定文件进行压缩
最新推荐文章于 2024-07-02 17:23:19 发布