import os import zipfile as zip def do_zip(source_, target_file): ''' zip文件压缩 :param source_: 原始文件路径 :param target_file: 目标文件路径 :return: ''' zip_file = zip.ZipFile(target_file, 'w') pre_len = len(os.path.dirname(source_)) for parent, dirnames, filenames in os.walk(source_): for filename in filenames: print(f'{filename}') path_file = os.path.join(parent, filename) arcname = path_file[pre_len:].strip(os.path.sep) zip_file.write(path_file, arcname) ''' 单文件 ''' if os.path.isfile(source_): zip_file.write(source_,source_[pre_len:].strip(os.path.sep),) zip_file.close() do_zip("a.txt","test.zip")