如何写一个脚本定时整理文件夹

wen 实用脚本 1

本文目录导读:

如何写一个脚本定时整理文件夹

  1. Python版本(功能最全面)
  2. Windows批处理版本
  3. Linux Shell脚本版本
  4. 设置定时任务
  5. 使用方法

我来帮你写一个定时整理文件夹的脚本,这里提供几个不同场景的版本:

Python版本(功能最全面)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 文件夹整理脚本 - cleanup.py
import os
import shutil
import time
import schedule
from datetime import datetime
import logging
# 配置
FOLDER_PATH = "/path/to/your/folder"  # 要整理的文件夹路径
SORTED_BY_TYPE = True  # 按文件类型分类
MAX_AGE_DAYS = 30  # 超过30天的文件放入归档
LOG_FILE = "cleanup.log"
# 文件类型分类
FILE_CATEGORIES = {
    'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'],
    'documents': ['.pdf', '.doc', '.docx', '.txt', '.xlsx', '.pptx'],
    'videos': ['.mp4', '.avi', '.mkv', '.mov', '.wmv'],
    'music': ['.mp3', '.wav', '.flac', '.aac'],
    'archives': ['.zip', '.rar', '.7z', '.tar', '.gz'],
    'code': ['.py', '.js', '.html', '.css', '.java', '.cpp'],
}
def setup_logging():
    """设置日志"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(LOG_FILE),
            logging.StreamHandler()
        ]
    )
def get_file_category(filename):
    """获取文件类别"""
    ext = os.path.splitext(filename)[1].lower()
    for category, extensions in FILE_CATEGORIES.items():
        if ext in extensions:
            return category
    return 'others'
def clean_old_files(folder_path, max_days):
    """清理旧文件"""
    now = time.time()
    for item in os.listdir(folder_path):
        item_path = os.path.join(folder_path, item)
        if os.path.isfile(item_path):
            # 检查文件年龄
            file_age_days = (now - os.path.getmtime(item_path)) / (24 * 3600)
            if file_age_days > max_days:
                # 移动到归档文件夹
                archive_dir = os.path.join(folder_path, "archive")
                os.makedirs(archive_dir, exist_ok=True)
                shutil.move(item_path, os.path.join(archive_dir, item))
                logging.info(f"归档旧文件: {item}")
def organize_by_type(folder_path):
    """按文件类型整理"""
    for item in os.listdir(folder_path):
        item_path = os.path.join(folder_path, item)
        if os.path.isfile(item_path):
            category = get_file_category(item)
            category_dir = os.path.join(folder_path, category)
            os.makedirs(category_dir, exist_ok=True)
            shutil.move(item_path, os.path.join(category_dir, item))
            logging.info(f"移动文件: {item} -> {category}/")
def cleanup_empty_folders(folder_path):
    """清理空文件夹"""
    for item in os.listdir(folder_path):
        item_path = os.path.join(folder_path, item)
        if os.path.isdir(item_path):
            try:
                os.rmdir(item_path)  # 只删除空文件夹
                logging.info(f"删除空文件夹: {item}")
            except OSError:
                pass  # 文件夹非空
def main_task():
    """主任务函数"""
    logging.info("开始整理文件夹...")
    if not os.path.exists(FOLDER_PATH):
        logging.error(f"文件夹不存在: {FOLDER_PATH}")
        return
    try:
        # 按类型整理
        if SORTED_BY_TYPE:
            organize_by_type(FOLDER_PATH)
        # 清理旧文件
        clean_old_files(FOLDER_PATH, MAX_AGE_DAYS)
        # 清理空文件夹
        cleanup_empty_folders(FOLDER_PATH)
        logging.info("文件夹整理完成!")
    except Exception as e:
        logging.error(f"整理过程出错: {str(e)}")
def main():
    setup_logging()
    # 立即执行一次
    main_task()
    # 设置定时任务(每天凌晨2点执行)
    schedule.every().day.at("02:00").do(main_task)
    # 也可以设置每小时的执行
    # schedule.every(1).hours.do(main_task)
    logging.info("定时整理脚本已启动...")
    while True:
        schedule.run_pending()
        time.sleep(60)  # 每分钟检查一次
if __name__ == "__main__":
    main()

Windows批处理版本

@echo off
:: cleanup.bat - Windows文件夹整理脚本
set TARGET_FOLDER=C:\Users\YourName\Downloads
set LOG_FILE=C:\Temp\cleanup.log
echo %date% %time% - 开始整理文件夹 >> %LOG_FILE%
:: 按文件类型创建子文件夹并移动文件
for %%f in ("%TARGET_FOLDER%\*.jpg", "%TARGET_FOLDER%\*.png", "%TARGET_FOLDER%\*.gif") do (
    if not exist "%TARGET_FOLDER%\Images" mkdir "%TARGET_FOLDER%\Images"
    move "%%f" "%TARGET_FOLDER%\Images\" >> %LOG_FILE%
)
for %%f in ("%TARGET_FOLDER%\*.pdf", "%TARGET_FOLDER%\*.doc", "%TARGET_FOLDER%\*.docx") do (
    if not exist "%TARGET_FOLDER%\Documents" mkdir "%TARGET_FOLDER%\Documents"
    move "%%f" "%TARGET_FOLDER%\Documents\" >> %LOG_FILE%
)
for %%f in ("%TARGET_FOLDER%\*.mp4", "%TARGET_FOLDER%\*.avi", "%TARGET_FOLDER%\*.mkv") do (
    if not exist "%TARGET_FOLDER%\Videos" mkdir "%TARGET_FOLDER%\Videos"
    move "%%f" "%TARGET_FOLDER%\Videos\" >> %LOG_FILE%
)
:: 删除大于30天的文件
forfiles /p "%TARGET_FOLDER%" /s /m *.* /d -30 /c "cmd /c del @path && echo 删除旧文件: @path >> %LOG_FILE%" 2>nul
:: 删除空文件夹
for /f "delims=" %%d in ('dir "%TARGET_FOLDER%" /ad /b /s ^| sort /r') do (
    rd "%%d" 2>nul && echo 删除空文件夹: %%d >> %LOG_FILE%
)
echo %date% %time% - 文件夹整理完成 >> %LOG_FILE%

Linux Shell脚本版本

#!/bin/bash
# cleanup.sh - Linux文件夹整理脚本
# 配置
TARGET_DIR="$HOME/Downloads"
LOG_FILE="$HOME/cleanup.log"
MAX_FILE_AGE=30  # 天数
# 日志函数
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1"
}
# 按类型整理函数
organize_files() {
    log_message "开始按类型整理文件..."
    # 创建分类目录并移动文件
    declare -A categories
    categories=(
        ["Images"]=".jpg .jpeg .png .gif .bmp"
        ["Documents"]=".pdf .doc .docx .txt .xlsx"
        ["Videos"]=".mp4 .avi .mkv .mov"
        ["Music"]=".mp3 .wav .flac"
        ["Archives"]=".zip .rar .7z .tar.gz"
        ["Scripts"]=".sh .py .js .html"
    )
    for category in "${!categories[@]}"; do
        mkdir -p "$TARGET_DIR/$category"
        for ext in ${categories[$category]}; do
            find "$TARGET_DIR" -maxdepth 1 -type f -name "*$ext" -exec mv {} "$TARGET_DIR/$category/" \; 2>/dev/null
        done
    done
    # 处理其他文件
    mkdir -p "$TARGET_DIR/Others"
    find "$TARGET_DIR" -maxdepth 1 -type f -exec sh -c '
        for f do
            ext="${f##*.}"
            case "$ext" in
                jpg|jpeg|png|gif|pdf|doc|docx|mp4|avi|mp3|zip|sh|py) ;;
                *) mv "$f" "$TARGET_DIR/Others/" ;;
            esac
        done
    ' sh {} +
}
# 清理旧文件
clean_old_files() {
    log_message "清理超过${MAX_FILE_AGE}天的文件..."
    find "$TARGET_DIR" -type f -mtime +$MAX_FILE_AGE -exec rm {} \; 2>&1
}
# 清理空文件夹
clean_empty_dirs() {
    log_message "清理空文件夹..."
    find "$TARGET_DIR" -type d -empty -delete 2>&1
}
# 主函数
main() {
    # 检查目录是否存在
    if [ ! -d "$TARGET_DIR" ]; then
        log_message "错误: 目录 $TARGET_DIR 不存在"
        exit 1
    fi
    log_message "=== 开始整理 ==="
    organize_files
    clean_old_files
    clean_empty_dirs
    log_message "=== 整理完成 ==="
    echo "----------------------------------------" >> "$LOG_FILE"
}
# 执行主函数
main

设置定时任务

Windows (使用任务计划程序):

# 创建定时任务
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "C:\scripts\cleanup.bat"
$trigger = New-ScheduledTaskTrigger -Daily -At "02:00AM"
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask -TaskName "FolderCleanup" `
    -Action $action `
    -Trigger $trigger `
    -Principal $principal `
    -Settings $settings

Linux (使用crontab):

# 编辑crontab
crontab -e
# 添加以下行(每天凌晨2点执行)
0 2 * * * /path/to/cleanup.sh
# 其他例子:
# 每小时执行
# 0 * * * * /path/to/cleanup.sh
# 每周日执行
# 0 2 * * 0 /path/to/cleanup.sh

使用方法

  1. Python版本

    • 安装依赖:pip install schedule
    • 修改配置中的 FOLDER_PATH
    • 运行:python cleanup.py
  2. Windows版本

    • 修改 TARGET_FOLDER 路径
    • 使用任务计划程序设置定时
  3. Linux版本

    • 赋予执行权限:chmod +x cleanup.sh
    • 修改 TARGET_DIR 路径
    • 使用 crontab 设置定时

选择最适合你需求的版本,记得先测试再正式使用!

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