import os,shutil import zipfile from logs import log def zip_file(folderPath, outputZipPath=None): """ 压缩指定目录为zip文件 Args: folderPath: 要压缩的目录路径 outputZipPath: 输出的zip文件路径,如果为None则使用目录名+'.zip' Returns: str: 生成的zip文件路径,如果失败返回None """ try: if not os.path.exists(folderPath): log(f"目录不存在: {folderPath}") return None if not os.path.isdir(folderPath): log(f"路径不是目录: {folderPath}") return None # 如果没有指定输出路径,使用目录名+'.zip' if outputZipPath is None: folderName = os.path.basename(folderPath.rstrip(os.sep)) parentDir = os.path.dirname(folderPath) outputZipPath = os.path.join(parentDir, f"{folderName}.zip") log(f"开始压缩目录: {folderPath} -> {outputZipPath}") # 创建zip文件 with zipfile.ZipFile(outputZipPath, 'w', zipfile.ZIP_DEFLATED) as zipf: # 遍历目录中的所有文件 for root, dirs, files in os.walk(folderPath): # 计算相对路径 # 如果root就是folderPath,相对路径为空 # 否则计算相对于folderPath的路径 if root == folderPath: arcname_prefix = '' else: # 获取相对于folderPath的路径 arcname_prefix = os.path.relpath(root, folderPath) + os.sep for filename in files: file_path = os.path.join(root, filename) # 在zip中的路径(相对路径) arcname = arcname_prefix + filename zipf.write(file_path, arcname) log(f"已添加文件到压缩包: {arcname}") log(f"目录压缩完成: {outputZipPath}") return outputZipPath except Exception as e: log(f"压缩目录时出现错误: {str(e)}") return None # def uploadAndZip(folderPath): # # 上传文件到oss # # upload_file(folderPath) # 暂时注释,等待实现 # # 压缩文件 # zip_file(folderPath) zip_file("/Users/dcx/code/make2/script/batchPrint/1","1024.zip")