如何编写下载文件夹整理脚本

wen 实用脚本 27

本文目录导读:

如何编写下载文件夹整理脚本

  1. 基础版 - 按文件类型分类
  2. 进阶版 - 带日期和日志
  3. 自动化版本 - 设置定时任务
  4. 使用说明

我来帮你编写一个下载文件夹整理脚本,这里提供多个版本,你可以根据需求选择。

基础版 - 按文件类型分类

Windows (PowerShell)

# 下载文件夹整理脚本 - 按文件类型分类
$downloadPath = "$env:USERPROFILE\Downloads"
# 定义文件类型分类规则
$categories = @{
    "图片" = @(".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".webp", ".ico")
    "文档" = @(".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".txt", ".md")
    "视频" = @(".mp4", ".avi", ".mkv", ".mov", ".wmv", ".flv")
    "音频" = @(".mp3", ".wav", ".flac", ".aac", ".ogg")
    "压缩包" = @(".zip", ".rar", ".7z", ".tar", ".gz")
    "安装包" = @(".exe", ".msi", ".dmg", ".app", ".deb", ".rpm")
    "代码" = @(".py", ".js", ".html", ".css", ".json", ".xml", ".sql")
}
# 创建分类文件夹
foreach ($category in $categories.Keys) {
    $folderPath = Join-Path $downloadPath $category
    if (-not (Test-Path $folderPath)) {
        New-Item -ItemType Directory -Path $folderPath
        Write-Host "创建文件夹: $category"
    }
}
# 移动文件到对应分类
Get-ChildItem -Path $downloadPath -File | ForEach-Object {
    $file = $_
    $fileExtension = $file.Extension.ToLower()
    foreach ($category in $categories.Keys) {
        if ($categories[$category] -contains $fileExtension) {
            $destination = Join-Path $downloadPath $category $file.Name
            Move-Item -Path $file.FullName -Destination $destination
            Write-Host "移动文件: $($file.Name) -> $category"
            break
        }
    }
}
Write-Host "整理完成!"

Linux/macOS (Bash)

#!/bin/bash
# 下载文件夹整理脚本
DOWNLOAD_PATH="$HOME/Downloads"
# 定义文件类型分类规则
declare -A categories
categories[图片]="jpg jpeg png gif bmp svg webp ico"
categories[文档]="pdf doc docx xls xlsx ppt pptx txt md"
categories[视频]="mp4 avi mkv mov wmv flv"
categories[音频]="mp3 wav flac aac ogg"
categories[压缩包]="zip rar 7z tar gz"
categories[安装包]="exe msi dmg app deb rpm"
categories[代码]="py js html css json xml sql sh"
# 创建分类文件夹
for category in "${!categories[@]}"; do
    folder="$DOWNLOAD_PATH/$category"
    if [ ! -d "$folder" ]; then
        mkdir -p "$folder"
        echo "创建文件夹: $category"
    fi
done
# 遍历并移动文件
cd "$DOWNLOAD_PATH"
for file in *; do
    if [ -f "$file" ]; then
        extension="${file##*.}"
        extension=$(echo "$extension" | tr '[:upper:]' '[:lower:]')
        for category in "${!categories[@]}"; do
            if [[ "${categories[$category]}" == *"$extension"* ]]; then
                mv "$file" "$category/"
                echo "移动文件: $file -> $category"
                break
            fi
        done
    fi
done
echo "整理完成!"

进阶版 - 带日期和日志

Python 版本 (跨平台)

import os
import shutil
import datetime
import logging
from pathlib import Path
# 配置
DOWNLOAD_PATH = Path.home() / "Downloads"
LOG_FILE = DOWNLOAD_PATH / "整理日志.txt"
# 设置日志
logging.basicConfig(
    filename=LOG_FILE,
    level=logging.INFO,
    format='%(asctime)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
# 文件分类规则
CATEGORIES = {
    "图片": ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.ico'],
    "文档": ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.md'],
    "视频": ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv'],
    "音频": ['.mp3', '.wav', '.flac', '.aac', '.ogg'],
    "压缩包": ['.zip', '.rar', '.7z', '.tar', '.gz'],
    "安装包": ['.exe', '.msi', '.dmg', '.app', '.deb', '.rpm'],
    "代码": ['.py', '.js', '.html', '.css', '.json', '.xml', '.sql', '.sh'],
}
def create_folders():
    """创建分类文件夹"""
    for category in CATEGORIES.keys():
        folder_path = DOWNLOAD_PATH / category
        folder_path.mkdir(exist_ok=True)
        print(f"创建文件夹: {category}")
def organize_files():
    """整理文件"""
    moved_count = 0
    error_count = 0
    for file_path in DOWNLOAD_PATH.iterdir():
        if file_path.is_file() and file_path.name != LOG_FILE:
            file_extension = file_path.suffix.lower()
            file_category = None
            # 查找文件类型
            for category, extensions in CATEGORIES.items():
                if file_extension in extensions:
                    file_category = category
                    break
            # 如果找到了分类,移动文件
            if file_category:
                destination = DOWNLOAD_PATH / file_category / file_path.name
                try:
                    # 如果目标文件已存在,重命名
                    if destination.exists():
                        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
                        new_name = f"{file_path.stem}_{timestamp}{file_extension}"
                        destination = DOWNLOAD_PATH / file_category / new_name
                    shutil.move(str(file_path), str(destination))
                    message = f"移动: {file_path.name} -> {file_category}"
                    print(message)
                    logging.info(message)
                    moved_count += 1
                except Exception as e:
                    error_msg = f"错误: 无法移动 {file_path.name} - {str(e)}"
                    print(error_msg)
                    logging.error(error_msg)
                    error_count += 1
    return moved_count, error_count
def main():
    print("="*50)
    print("下载文件夹整理工具")
    print(f"目标路径: {DOWNLOAD_PATH}")
    print("="*50)
    # 创建文件夹
    create_folders()
    # 整理文件
    moved, errors = organize_files()
    # 显示结果
    print("\n" + "="*50)
    print(f"整理完成!")
    print(f"- 成功移动: {moved} 个文件")
    print(f"- 处理失败: {errors} 个文件")
    print(f"- 日志文件: {LOG_FILE}")
    # 备份未分类文件到"其他"文件夹
    other_files = [f for f in DOWNLOAD_PATH.iterdir() 
                   if f.is_file() and f.name != LOG_FILE]
    if other_files:
        other_folder = DOWNLOAD_PATH / "其他"
        other_folder.mkdir(exist_ok=True)
        for file in other_files:
            shutil.move(str(file), str(other_folder / file.name))
        print(f"- 未分类文件移至: 其他")
if __name__ == "__main__":
    main()

自动化版本 - 设置定时任务

Windows 定时任务

# 创建计划任务(管理员权限)
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File C:\Scripts\整理下载.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "10:00AM"
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount
$task = New-ScheduledTask -Action $action -Trigger $trigger -Principal $principal
Register-ScheduledTask -TaskName "整理下载文件夹" -InputObject $task

Linux cron 任务

# 添加到 crontab (每天10点运行)
crontab -e
# 添加以下行
0 10 * * * /path/to/整理下载.sh

使用说明

  1. 保存脚本

    • Windows: 保存为 整理下载.ps1
    • Linux: 保存为 整理下载.sh,然后运行 chmod +x 整理下载.sh
    • Python: 保存为 整理下载.py
  2. 运行脚本

    # Windows PowerShell
    powershell.exe -ExecutionPolicy Bypass -File 整理下载.ps1
    # Linux/macOS
    ./整理下载.sh
    # Python (跨平台)
    python3 整理下载.py
  3. 自定义规则:修改脚本中的 CATEGORIES 字典添加或修改文件类型

选择适合你系统的版本,有问题欢迎继续提问!

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