运行之后输入要压缩的目录,只压缩目标目录下的子目录。
[Asm] 纯文本查看 复制代码 import os
import zipfile
def compress_directory(dir_path):
zip_filename = f"{dir_path}.zip"
if os.path.exists(zip_filename):
print(f"{zip_filename} 已经存在,跳过...")
return
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(dir_path):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, start=dir_path)
zipf.write(file_path, arcname)
print(f"{dir_path} 已经压缩到 {zip_filename}")
root_dir = input('文件夹地址:')
# 遍历 root_dir 目录下的子目录
for dir_name in os.listdir(root_dir):
full_dir_path = os.path.join(root_dir, dir_name)
if os.path.isdir(full_dir_path):
compress_directory(full_dir_path)
解压目标目录下的子目录压缩包
[Asm] 纯文本查看 复制代码 import os
import zipfile
def unzip_all_zip_files(directory):
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.zip'):
zip_file_path = os.path.join(root, file)
target_dir = os.path.splitext(zip_file_path)[0]
if not os.path.exists(target_dir): # 跳过已存在的目录
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
zip_ref.extractall(target_dir)
print(f"已解压文件 '{file}' 到目录 '{target_dir}'")
# 指定目录
directory_to_extract = input('文件夹地址:')
# 解压所有 zip 文件
unzip_all_zip_files(directory_to_extract)
|