脚本如何批量压缩文件

wen 实用脚本 21

本文目录导读:

脚本如何批量压缩文件

  1. Python脚本(最灵活)
  2. 批处理脚本(Windows)
  3. Shell脚本(Linux/Mac)
  4. PowerShell脚本(Windows)
  5. 高级Python脚本(带进度条和错误处理)
  6. 使用命令行工具
  7. 注意事项:

Python脚本(最灵活)

使用 zipfile 模块

import os
import zipfile
from pathlib import Path
def batch_zip(source_dir, output_dir=None):
    """
    批量压缩文件夹中的每个子文件夹
    """
    source_path = Path(source_dir)
    if output_dir is None:
        output_dir = source_path / "compressed"
    output_path = Path(output_dir)
    output_path.mkdir(exist_ok=True)
    for folder in source_path.iterdir():
        if folder.is_dir():
            zip_name = f"{folder.name}.zip"
            zip_path = output_path / zip_name
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for file_path in folder.rglob('*'):
                    arcname = str(file_path.relative_to(folder))
                    zipf.write(file_path, arcname)
            print(f"已压缩: {folder.name}")
# 使用示例
batch_zip("/path/to/source/folder")

压缩特定文件类型

import os
import zipfile
def zip_specific_files(directory, extension='.txt'):
    """
    压缩指定目录下特定扩展名的文件
    """
    zip_name = f"{os.path.basename(directory)}_{extension[1:]}.zip"
    with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(directory):
            for file in files:
                if file.endswith(extension):
                    file_path = os.path.join(root, file)
                    arcname = os.path.relpath(file_path, directory)
                    zipf.write(file_path, arcname)
    print(f"已创建: {zip_name}")
# 使用示例
zip_specific_files("/path/to/folder", ".txt")

批处理脚本(Windows)

@echo off
setlocal enabledelayedexpansion
REM 设置源文件夹
set "SOURCE_DIR=C:\YourFolder"
set "OUTPUT_DIR=C:\CompressedFiles"
REM 创建输出目录
if not exist "%OUTPUT_DIR%" mkdir "%OUTPUT_DIR%"
REM 遍历子文件夹
for /d %%i in ("%SOURCE_DIR%\*") do (
    echo 正在压缩: %%~ni
    powershell -command "Compress-Archive -Path '%%i\*' -DestinationPath '%OUTPUT_DIR%\%%~ni.zip' -Force"
)
echo 压缩完成!
pause

Shell脚本(Linux/Mac)

使用 tar + gzip

#!/bin/bash
# 批量压缩文件夹
SOURCE_DIR="/path/to/source"
OUTPUT_DIR="/path/to/output"
mkdir -p "$OUTPUT_DIR"
for dir in "$SOURCE_DIR"/*/; do
    dirname=$(basename "$dir")
    echo "正在压缩: $dirname"
    tar -czf "$OUTPUT_DIR/$dirname.tar.gz" -C "$SOURCE_DIR" "$dirname"
done
echo "压缩完成!"

使用 zip 命令

#!/bin/bash
SOURCE_DIR="/path/to/source"
OUTPUT_DIR="/path/to/output"
mkdir -p "$OUTPUT_DIR"
cd "$SOURCE_DIR"
for dir in */; do
    dirname="${dir%/}"
    echo "正在压缩: $dirname"
    zip -r "$OUTPUT_DIR/$dirname.zip" "$dirname"
done
echo "压缩完成!"

PowerShell脚本(Windows)

# 批量压缩脚本
$sourcePath = "C:\YourFolder"
$outputPath = "C:\CompressedFiles"
# 创建输出目录
if (-not (Test-Path $outputPath)) {
    New-Item -ItemType Directory -Path $outputPath
}
# 获取所有子文件夹
$folders = Get-ChildItem -Path $sourcePath -Directory
foreach ($folder in $folders) {
    $zipPath = Join-Path $outputPath ($folder.Name + ".zip")
    Write-Host "正在压缩: $($folder.Name)"
    # 使用 .NET 类进行压缩
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    [System.IO.Compression.ZipFile]::CreateFromDirectory($folder.FullName, $zipPath)
}
Write-Host "压缩完成!"

高级Python脚本(带进度条和错误处理)

import os
import zipfile
from pathlib import Path
from tqdm import tqdm
import concurrent.futures
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
def compress_folder(folder_path, output_dir):
    """压缩单个文件夹"""
    folder_name = folder_path.name
    zip_path = output_dir / f"{folder_name}.zip"
    try:
        with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for file_path in folder_path.rglob('*'):
                if file_path.is_file():
                    arcname = str(file_path.relative_to(folder_path))
                    zipf.write(file_path, arcname)
        return f"成功: {folder_name}"
    except Exception as e:
        return f"失败: {folder_name} - {str(e)}"
def batch_compress_advanced(source_dir, output_dir=None, max_workers=4):
    """高级批量压缩(多线程+进度条)"""
    source_path = Path(source_dir)
    if output_dir is None:
        output_dir = source_path.parent / f"{source_path.name}_compressed"
    output_path = Path(output_dir)
    output_path.mkdir(exist_ok=True, parents=True)
    # 获取所有子文件夹
    folders = [f for f in source_path.iterdir() if f.is_dir()]
    if not folders:
        print("未找到子文件夹")
        return
    print(f"找到 {len(folders)} 个文件夹开始压缩...")
    # 多线程压缩
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {
            executor.submit(compress_folder, folder, output_path): folder 
            for folder in folders
        }
        # 显示进度条
        for future in tqdm(concurrent.futures.as_completed(futures), 
                          total=len(folders), 
                          desc="压缩进度"):
            result = future.result()
            logging.info(result)
    print(f"\n压缩完成!文件保存在: {output_path}")
# 使用示例
batch_compress_advanced("/path/to/source")

使用命令行工具

Windows (用 7-Zip)

REM 批量压缩每个子文件夹
for /d %%i in ("C:\Source\*") do (
    "C:\Program Files\7-Zip\7z.exe" a -tzip "C:\Output\%%~ni.zip" "%%i\*"
)

Linux (用 parallel)

# 并行压缩
ls -d */ | parallel -j4 'tar -czf {}.tar.gz {}'

注意事项:

  1. 路径问题:使用绝对路径避免混淆
  2. 权限问题:确保有读写权限
  3. 磁盘空间:确认有足够空间存放压缩文件
  4. 文件编码:处理中文文件名注意编码问题
  5. 大文件:考虑使用分卷压缩或增量压缩

选择哪种方法取决于你的操作系统、文件数量和具体需求,Python脚本最灵活,批处理脚本在Windows上最简单。

抱歉,评论功能暂时关闭!