打包文件
压缩文件夹
import zipfile import os BASE_STATIC_CASE_RESULT=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#项目根目录 print(BASE_STATIC_CASE_RESULT) base_dir = os.path.join(BASE_STATIC_CASE_RESULT, 'report') # 要压缩文件夹的根路径 zip_file_name = 'report.zip' #打包后文件的文件名 f = zipfile.ZipFile(os.path.join(BASE_STATIC_CASE_RESULT, zip_file_name), 'w', zipfile.ZIP_DEFLATED) for dir_path, dir_name, file_names in os.walk(base_dir): # 要是不replace,就从根目录开始复制 file_path = dir_path.replace(base_dir, '') # 实现当前文件夹以及包含的所有文件 file_path = file_path and file_path + os.sep or '' for file_name in file_names: f.write(os.path.join(dir_path, file_name), file_path + file_name) f.close()
解压文件夹
import zipfile def zip_files( files, zip_name ): zip = zipfile.ZipFile( zip_name, 'w', zipfile.ZIP_DEFLATED ) for file in files: print ('compressing', file) zip.write( file ) zip.close() print ('compressing finished') files = ['.\\123.txt','.\\3.txt']#文件的位置,多个文件用“,”隔开 zip_file = '.\\m66y.zip'#压缩包名字 zip_files(files, zip_file)