定时清空指定文件夹的脚本

wen 实用脚本 2

本文目录导读:

定时清空指定文件夹的脚本

  1. 方案1:Python 脚本(最灵活)
  2. 方案2:Linux/macOS 使用 cron
  3. 方案3:Windows PowerShell
  4. 方案4:Docker 定时任务
  5. 使用建议

我来帮你创建一个定时清空指定文件夹的脚本,这里提供几种不同场景的解决方案:

方案1:Python 脚本(最灵活)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
定时清空指定文件夹的脚本
支持 Windows / Linux / macOS
"""
import os
import shutil
import time
import schedule
import logging
from datetime import datetime
from pathlib import Path
# ========== 配置区域 ==========
TARGET_FOLDER = "/path/to/your/folder"  # 要清空的文件夹路径
RUN_TIME = "03:00"  # 每天执行时间 (24小时制)
DELETE_SUBFOLDERS = True  # 是否删除子文件夹
SAVE_EMPTY_FOLDER = True  # 是否保留空文件夹结构
# ========== 结束配置区域 ==========
# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('cleanup.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)
def clear_folder(folder_path):
    """清空指定文件夹"""
    try:
        folder = Path(folder_path)
        if not folder.exists():
            logger.error(f"文件夹不存在: {folder_path}")
            return False
        # 统计文件数量
        file_count = sum(1 for f in folder.rglob('*') if f.is_file())
        # 删除所有文件和子文件夹
        if DELETE_SUBFOLDERS:
            for item in folder.iterdir():
                if item.is_file() or item.is_symlink():
                    item.unlink()
                    logger.info(f"删除文件: {item}")
                elif item.is_dir():
                    shutil.rmtree(item)
                    logger.info(f"删除文件夹: {item}")
        else:
            # 只删除文件,保留子文件夹
            for item in folder.rglob('*'):
                if item.is_file():
                    item.unlink()
                    logger.info(f"删除文件: {item}")
        # 如果不保留空文件夹,则删除空子文件夹
        if not SAVE_EMPTY_FOLDER:
            for item in folder.rglob('*'):
                if item.is_dir() and not any(item.iterdir()):
                    item.rmdir()
        logger.info(f"✅ 成功清空 {file_count} 个文件")
        return True
    except Exception as e:
        logger.error(f"清理失败: {str(e)}")
        return False
def delete_old_files(folder_path, days):
    """
    只删除指定天数之前的文件
    """
    folder = Path(folder_path)
    if not folder.exists():
        logger.error(f"文件夹不存在: {folder_path}")
        return
    cutoff_time = time.time() - (days * 86400)
    deleted = 0
    for item in folder.rglob('*'):
        if item.is_file() and item.stat().st_mtime < cutoff_time:
            item.unlink()
            deleted += 1
            logger.info(f"删除过期文件: {item}")
    logger.info(f"✅ 清理了 {deleted} 个过期文件")
def main():
    """主函数"""
    logger.info("🚀 定时清空文件夹脚本启动")
    logger.info(f"目标文件夹: {TARGET_FOLDER}")
    logger.info(f"执行时间: {RUN_TIME}")
    # 立即执行一次(可选)
    # clear_folder(TARGET_FOLDER)
    # 每天定时执行
    schedule.every().day.at(RUN_TIME).do(clear_folder, TARGET_FOLDER)
    while True:
        schedule.run_pending()
        time.sleep(60)  # 每分钟检查一次
if __name__ == "__main__":
    # 手动执行一次(测试)
    clear_folder(TARGET_FOLDER)
    # 备份:清空3天前的文件(可选)
    # delete_old_files(TARGET_FOLDER, 3)
    # 启动定时任务
    main()

方案2:Linux/macOS 使用 cron

创建清理脚本 cleanup.sh

#!/bin/bash
# 清空指定文件夹脚本
TARGET_DIR="/path/to/your/folder"  # 要清理的目录
LOG_FILE="/var/log/cleanup.log"    # 日志文件
# 记录开始时间
echo "$(date '+%Y-%m-%d %H:%M:%S') - 开始清理 $TARGET_DIR" >> "$LOG_FILE"
# 方法1:删除所有内容(包括隐藏文件)
find "$TARGET_DIR" -mindepth 1 -exec rm -rf {} +
# 方法2:只删除文件,保留目录结构
# find "$TARGET_DIR" -type f -delete
# 方法3:删除空目录
# find "$TARGET_DIR" -type d -empty -delete
# 方法4:删除7天前的文件
# find "$TARGET_DIR" -type f -mtime +7 -delete
echo "$(date '+%Y-%m-%d %H:%M:%S') - 清理完成" >> "$LOG_FILE"

设置cron任务:

# 编辑cron配置
crontab -e
# 添加以下行(格式:分 时 日 月 周 命令)
# 每天凌晨3点执行
0 3 * * * /path/to/cleanup.sh
# 每周一凌晨3点执行
0 3 * * 1 /path/to/cleanup.sh

方案3:Windows PowerShell

创建 cleanup.ps1

# Windows PowerShell 定时清理脚本
$targetFolder = "C:\path\to\your\folder"  # 要清理的文件夹
$logFile = "C:\cleanup.log"
# 记录日志
Write-Host "$(Get-Date) - 开始清理 $targetFolder" | Out-File -Append $logFile
try {
    # 方法1:删除所有内容
    Get-ChildItem -Path $targetFolder -Force -ErrorAction SilentlyContinue | 
        ForEach-Object { 
            Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue 
        }
    # 方法2:只删除子文件夹内的文件
    # Get-ChildItem -Path $targetFolder -Recurse -File | Remove-Item -Force
    # 方法3:删除7天前的文件
    # $days = 7
    # $cutoffDate = (Get-Date).AddDays(-$days)
    # Get-ChildItem -Path $targetFolder -Recurse -File | 
    #     Where-Object { $_.LastWriteTime -lt $cutoffDate } | Remove-Item -Force
    Write-Host "$(Get-Date) - 清理完成" | Out-File -Append $logFile
}
catch {
    Write-Host "$(Get-Date) - 清理失败: $_" | Out-File -Append $logFile
}

创建计划任务:

# 以管理员身份运行
schtasks /Create /TN "ClearFolderTask" /TR "powershell.exe -WindowStyle Hidden -ExecutionPolicy Bypass -File C:\path\to\cleanup.ps1" /SC DAILY /ST 03:00

方案4:Docker 定时任务

docker-compose.yml

version: '3.8'
services:
  cleanup:
    image: alpine:latest
    container_name: folder-cleanup
    volumes:
      - ./target:/data:rw  # 挂载要清理的目录
    command: >
      sh -c "
      echo '0 3 * * * find /data -mindepth 1 -exec rm -rf {} + >> /var/log/cleanup.log 2>&1' > /etc/crontabs/root &&
      crond -f
      "

使用建议

  1. 先测试再使用:先在非重要目录测试脚本
  2. 备份重要数据:确保不会误删重要文件
  3. 日志记录:建议保留详细的日志便于排查
  4. 定时设置:选择业务低峰期执行
  5. 权限设置:确保脚本有足够的权限

选择适合你系统的方案,如需调整请告诉我具体情况!

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