脚本能自动压缩和解压文件吗?

wen 实用脚本 2

本文目录导读:

脚本能自动压缩和解压文件吗?

  1. Shell 脚本 (Linux/macOS)
  2. 批处理/PowerShell (Windows)
  3. Python 脚本 (跨平台)
  4. 自动定时压缩脚本
  5. 注意事项

是的,脚本完全可以实现自动压缩和解压文件,具体实现方式取决于你使用的操作系统和脚本语言,以下是常见的几种方案:

Shell 脚本 (Linux/macOS)

压缩

#!/bin/bash
# 压缩文件夹为 tar.gz
tar -czf archive.tar.gz /path/to/folder
# 压缩为 zip
zip -r archive.zip /path/to/folder

解压

#!/bin/bash
# 解压 tar.gz
tar -xzf archive.tar.gz
# 解压 zip
unzip archive.zip -d /target/folder

高级示例:自动压缩日志文件

#!/bin/bash
LOG_DIR="/var/log/myapp"
DAYS=7
# 压缩7天前的日志
find "$LOG_DIR" -name "*.log" -mtime +$DAYS -exec gzip {} \;

批处理/PowerShell (Windows)

批处理 (.bat)

@echo off
rem 使用 PowerShell 压缩
powershell -Command "Compress-Archive -Path C:\folder -DestinationPath C:\archive.zip"
rem 解压
powershell -Command "Expand-Archive -Path C:\archive.zip -DestinationPath C:\extracted"

PowerShell 脚本 (.ps1)

# 压缩
Compress-Archive -Path C:\Source\* -DestinationPath C:\Backup\backup.zip -Force
# 解压
Expand-Archive -Path C:\Backup\backup.zip -DestinationPath C:\Restored -Force

Python 脚本 (跨平台)

import zipfile
import tarfile
import os
# 压缩为 ZIP
def zip_folder(folder_path, output_path):
    with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                arcname = os.path.relpath(file_path, folder_path)
                zipf.write(file_path, arcname)
# 解压 ZIP
def unzip_file(zip_path, extract_path):
    with zipfile.ZipFile(zip_path, 'r') as zipf:
        zipf.extractall(extract_path)
# 使用示例
zip_folder('/path/to/folder', 'output.zip')
unzip_file('output.zip', '/path/to/extract')

自动定时压缩脚本

Linux crontab 示例

# 每天凌晨2点压缩日志
0 2 * * * /usr/local/bin/compress_logs.sh

Windows 任务计划程序

可使用 PowerShell 脚本配合任务计划程序实现定时压缩。

注意事项

  • 权限问题:脚本需要有对应文件的读写权限
  • 路径处理:建议使用绝对路径避免相对路径问题
  • 错误处理:添加错误检查,避免压缩失败影响后续操作
  • 大文件处理:考虑内存和磁盘空间限制

建议:如果只是简单的压缩解压任务,Shell 或批处理就足够了;如果需要更复杂的逻辑(如按规则筛选、加密、分卷压缩等),Python 更灵活。

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