本文目录导读:

我为您介绍几种批量解压压缩包文件的方法,涵盖Windows和Linux系统。
Windows系统方法
使用PowerShell脚本
# 批量解压当前文件夹所有.zip文件
Get-ChildItem -Path "C:\YourFolder" -Filter *.zip | ForEach-Object {
Expand-Archive -Path $_.FullName -DestinationPath "C:\ExtractedFolder\$($_.BaseName)" -Force
}
使用7-Zip命令行
@echo off
set "source=C:\YourFolder"
set "destination=C:\ExtractedFolder"
for %%f in ("%source%\*.zip") do (
"C:\Program Files\7-Zip\7z.exe" x "%%f" -o"%destination%\%%~nf" -y
)
使用PowerShell调用7-Zip(支持更多格式)
$7z = "C:\Program Files\7-Zip\7z.exe"
$source = "C:\YourFolder"
$destination = "C:\ExtractedFolder"
Get-ChildItem $source -Include *.zip, *.rar, *.7z -Recurse | ForEach-Object {
$outputPath = Join-Path $destination $_.BaseName
& $7z x $_.FullName "-o$outputPath" -y
}
Linux系统方法
批量解压.tar.gz文件
#!/bin/bash
for file in *.tar.gz; do
tar -xzf "$file" -C /目标目录
done
批量解压.zip文件(需要安装unzip)
#!/bin/bash
for file in *.zip; do
unzip -o "$file" -d "/目标目录/${file%.*}"
done
通用脚本(支持多种格式)
#!/bin/bash
# 批量解压脚本 - 支持zip/rar/tar.gz/tar.bz2等
for file in *; do
case "$file" in
*.zip) unzip -o "$file" -d "${file%.*}" ;;
*.rar) unrar x -o+ "$file" "${file%.*}/" ;;
*.tar.gz|*.tgz) tar -xzf "$file" -C "${file%.*}" ;;
*.tar.bz2) tar -xjf "$file" -C "${file%.*}" ;;
*.7z) 7z x "$file" -o"${file%.*}" -y ;;
esac
done
Python通用脚本
import zipfile
import os
import tarfile
import rarfile # 需要安装:pip install rarfile
import py7zr # 需要安装:pip install py7zr
def batch_extract(source_dir, dest_dir):
"""批量解压各种格式压缩包"""
os.makedirs(dest_dir, exist_ok=True)
for filename in os.listdir(source_dir):
filepath = os.path.join(source_dir, filename)
# 创建对应的输出目录
output_dir = os.path.join(dest_dir, os.path.splitext(filename)[0])
os.makedirs(output_dir, exist_ok=True)
try:
if filename.endswith('.zip'):
with zipfile.ZipFile(filepath, 'r') as zip_ref:
zip_ref.extractall(output_dir)
elif filename.endswith('.tar.gz') or filename.endswith('.tgz'):
with tarfile.open(filepath, 'r:gz') as tar_ref:
tar_ref.extractall(output_dir)
elif filename.endswith('.rar'):
with rarfile.RarFile(filepath) as rar_ref:
rar_ref.extractall(output_dir)
elif filename.endswith('.7z'):
with py7zr.SevenZipFile(filepath, mode='r') as z:
z.extractall(output_dir)
print(f"✓ 解压成功: {filename}")
except Exception as e:
print(f"✗ 解压失败: {filename} - {str(e)}")
# 使用示例
batch_extract("原始文件夹路径", "解压目标路径")
使用建议
-
安装必要工具:
- Windows: 安装7-Zip(免费开源)
- Linux:
sudo apt install p7zip-full unrar unzip
-
注意事项:
- 始终确认解压路径有足够空间
- 对于密码保护的压缩包需要额外处理
- 可以先在测试文件夹运行脚本
-
性能优化:
- 对于大量文件,使用多线程处理
- 解压后删除原始压缩包可释放空间
您可以根据具体需求选择合适的脚本,需要我详细讲解某个方法的实现细节吗?