py7zr 是开源库,详情请参考Github:py7zr
代码简单示范压缩:(解压的方法类似,可参考github上的示例)
- 代码py文件的路径如下:
- 压缩文件的路径:
- 压缩后的7z文件路径如下:
import os import py7zr import time #获取py文件所在路径 dir = os.path.dirname(os.path.realpath('__file__')) #系统时间 now_date = time.strftime("%Y-%m-%d") #压缩档名称 archive_name = now_date "_MarketData.7z" archive = py7zr.SevenZipFile(archive_name, 'w') ##压缩文件夹路径 data_file = dir "\\data" if os.path.exists(data_file): for dir_path, dir_names, file_names in os.walk(data_file): for filename in file_names: print(filename) fpath = dir_path.replace(data_file, '') file_path = os.path.join(dir_path, filename) filename = os.path.join(fpath, filename) archive.write(file_path, arcname=filename) archive.close() print("压缩完成!") else: print("文件不存在。") else: print("文件不存在。")
代码参考了 python使用py7zr做加密压缩