自动整理桌面文件的脚本

wen 实用脚本 1

本文目录导读:

自动整理桌面文件的脚本

  1. Windows 版本 (PowerShell)
  2. Linux/Mac 版本 (Bash)
  3. 使用方法
  4. 智能整理版 (Python 跨平台)
  5. Python 版本使用方法:
  6. 运行效果

我来帮你创建一个自动整理桌面文件的脚本,这个脚本会根据文件扩展名自动分类并移动到对应文件夹。

Windows 版本 (PowerShell)

# 桌面文件自动整理脚本
# 保存为: organize_desktop.ps1
# 获取桌面路径
$DesktopPath = [Environment]::GetFolderPath('Desktop')
Write-Host "正在整理桌面: $DesktopPath" -ForegroundColor Green
# 定义文件分类规则
$Categories = @{
    '图片' = @('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.ico', '.webp', '.svg')
    '视频' = @('.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv')
    '音频' = @('.mp3', '.wav', '.flac', '.aac', '.ogg')
    '文档' = @('.doc', '.docx', '.txt', '.pdf', '.xls', '.xlsx', '.ppt', '.pptx', '.md')
    '压缩包' = @('.zip', '.rar', '.7z', '.tar', '.gz')
    '程序' = @('.exe', '.msi', '.bat', '.cmd', '.ps1')
    '代码' = @('.py', '.js', '.html', '.css', '.java', '.cpp', '.h', '.c')
    '安装包' = @('.dmg', '.pkg', '.deb', '.rpm')
    '快捷方式' = @('.lnk', '.url')
    '其他' = @('*')
}
# 创建文件夹并移动文件
function Move-Files {
    param($Extension, $Category)
    if ($Extension -eq '*') {
        # 处理其他类型的文件
        $files = Get-ChildItem -Path $DesktopPath -File | Where-Object {
            $_.Extension -notmatch '\.(jpg|jpeg|png|gif|bmp|ico|webp|svg|mp4|avi|mkv|mov|wmv|flv|mp3|wav|flac|aac|ogg|doc|docx|txt|pdf|xls|xlsx|ppt|pptx|md|zip|rar|7z|tar|gz|exe|msi|bat|cmd|ps1|py|js|html|css|java|cpp|h|c|dmg|pkg|deb|rpm|lnk|url)$'
        }
    } else {
        $files = Get-ChildItem -Path $DesktopPath -File | Where-Object { $_.Extension -eq $Extension }
    }
    if ($files.Count -gt 0) {
        $targetFolder = Join-Path $DesktopPath $Category
        if (-not (Test-Path $targetFolder)) {
            New-Item -ItemType Directory -Path $targetFolder | Out-Null
        }
        foreach ($file in $files) {
            $targetPath = Join-Path $targetFolder $file.Name
            # 处理重名文件
            $counter = 1
            while (Test-Path $targetPath) {
                $newName = "$($file.BaseName)_$counter$($file.Extension)"
                $targetPath = Join-Path $targetFolder $newName
                $counter++
            }
            Move-Item $file.FullName $targetPath -Force
            Write-Host "已移动: $($file.Name) -> $Category/" -ForegroundColor Yellow
        }
    }
}
# 执行整理
foreach ($category in $Categories.Keys) {
    $extensions = $Categories[$category]
    foreach ($ext in $extensions) {
        Move-Files -Extension $ext -Category $category
    }
}
Write-Host "`n桌面整理完成!" -ForegroundColor Green

Linux/Mac 版本 (Bash)

#!/bin/bash
# 桌面文件自动整理脚本
# 保存为: organize_desktop.sh
# 使用方法: chmod +x organize_desktop.sh && ./organize_desktop.sh
# 获取桌面路径
DESKTOP_DIR="$HOME/Desktop"
if [[ ! -d "$DESKTOP_DIR" ]]; then
    DESKTOP_DIR="$HOME/桌面" # 中文系统尝试
fi
echo "正在整理桌面: $DESKTOP_DIR"
cd "$DESKTOP_DIR" || exit 1
# 创建分类函数
mkdir_dirs() {
    mkdir -p "图片" "视频" "音频" "文档" "压缩包" "程序" "代码" "安装包" "其他"
}
# 移动文件函数
move_files() {
    local pattern="$1"
    local category="$2"
    shopt -s nullglob
    for file in $pattern; do
        if [[ -f "$file" ]]; then
            mv "$file" "$category/"
            echo "已移动: $file -> $category/"
        fi
    done
    shopt -u nullglob
}
# 创建目录
mkdir_dirs
# 图片文件
move_files "*.jpg" "图片"
move_files "*.jpeg" "图片"
move_files "*.png" "图片"
move_files "*.gif" "图片"
move_files "*.bmp" "图片"
move_files "*.ico" "图片"
move_files "*.webp" "图片"
move_files "*.svg" "图片"
# 视频文件
move_files "*.mp4" "视频"
move_files "*.avi" "视频"
move_files "*.mkv" "视频"
move_files "*.mov" "视频"
move_files "*.wmv" "视频"
move_files "*.flv" "视频"
# 音频文件
move_files "*.mp3" "音频"
move_files "*.wav" "音频"
move_files "*.flac" "音频"
move_files "*.aac" "音频"
move_files "*.ogg" "音频"
# 文档文件
move_files "*.doc" "文档"
move_files "*.docx" "文档"
move_files "*.txt" "文档"
move_files "*.pdf" "文档"
move_files "*.xls" "文档"
move_files "*.xlsx" "文档"
move_files "*.ppt" "文档"
move_files "*.pptx" "文档"
move_files "*.md" "文档"
# 压缩文件
move_files "*.zip" "压缩包"
move_files "*.rar" "压缩包"
move_files "*.7z" "压缩包"
move_files "*.tar" "压缩包"
move_files "*.gz" "压缩包"
# 程序文件
move_files "*.exe" "程序"
move_files "*.msi" "程序"
move_files "*.sh" "程序"
move_files "*.bat" "程序"
# 代码文件
move_files "*.py" "代码"
move_files "*.js" "代码"
move_files "*.html" "代码"
move_files "*.css" "代码"
move_files "*.java" "代码"
move_files "*.cpp" "代码"
# 安装包
move_files "*.dmg" "安装包"
move_files "*.pkg" "安装包"
move_files "*.deb" "安装包"
move_files "*.rpm" "安装包"
# 其他文件
shopt -s nullglob
for file in *; do
    if [[ -f "$file" ]]; then
        mv "$file" "其他/"
        echo "已移动: $file -> 其他/"
    fi
done
shopt -u nullglob
echo "桌面整理完成!"

使用方法

Windows 用户:

  1. 将 PowerShell 代码保存为 organize_desktop.ps1
  2. 右键单击文件,选择“使用 PowerShell 运行”
  3. 如果遇到执行策略问题,运行:Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Mac/Linux 用户:

  1. 将 Bash 代码保存为 organize_desktop.sh
  2. 在终端赋予执行权限:
    chmod +x organize_desktop.sh
  3. 运行脚本:
    ./organize_desktop.sh

智能整理版 (Python 跨平台)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 功能更强大的跨平台桌面整理工具
import os
import shutil
from pathlib import Path
import platform
def get_desktop_path():
    """获取桌面路径"""
    system = platform.system()
    if system == "Windows":
        return Path.home() / "Desktop"
    elif system == "Darwin":  # macOS
        return Path.home() / "Desktop"
    else:  # Linux
        # 尝试常见路径
        desktop = Path.home() / "Desktop"
        if not desktop.exists():
            desktop = Path.home() / "桌面"
        return desktop
def create_categories():
    """创建分类目录"""
    categories = [
        "图片", "视频", "音频", "文档", "压缩包", 
        "程序", "代码", "安装包", "电子书", "其他"
    ]
    for cat in categories:
        (DESKTOP / cat).mkdir(exist_ok=True)
def get_category(ext):
    """根据扩展名返回分类"""
    ext = ext.lower()
    categories = {
        "图片": {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.ico', '.webp', '.svg', '.tiff', '.raw'},
        "视频": {'.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.mpg', '.mpeg'},
        "音频": {'.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a', '.wma'},
        "文档": {'.doc', '.docx', '.txt', '.pdf', '.xls', '.xlsx', '.ppt', '.pptx', '.md', '.rtf', '.odt'},
        "压缩包": {'.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz'},
        "程序": {'.exe', '.msi', '.bat', '.cmd', '.sh', '.app', '.com'},
        "代码": {'.py', '.js', '.html', '.css', '.java', '.cpp', '.h', '.c', '.php', '.swift', '.go', '.ts'},
        "安装包": {'.dmg', '.pkg', '.deb', '.rpm', '.iso'},
        "电子书": {'.epub', '.mobi', '.azw3', '.fb2', '.djvu'}
    }
    for category, exts in categories.items():
        if ext in exts:
            return category
    return "其他"
def organize_files():
    """整理文件"""
    moved_count = 0
    # 遍历桌面所有文件
    for item in DESKTOP.iterdir():
        if not item.is_file():
            continue
        # 跳过脚本自身和隐藏文件
        if item.name.startswith('.'):
            continue
        if item.name in ['organize_desktop.py', 'organize_desktop.sh', 'organize_desktop.ps1']:
            continue
        # 获取分类
        ext = item.suffix
        category = get_category(ext)
        # 目标路径
        target_dir = DESKTOP / category
        target_path = target_dir / item.name
        # 处理重名文件
        counter = 1
        while target_path.exists():
            new_name = f"{item.stem}_{counter}{item.suffix}"
            target_path = target_dir / new_name
            counter += 1
        try:
            shutil.move(str(item), str(target_path))
            print(f"✓ 已移动: {item.name} → {category}/")
            moved_count += 1
        except Exception as e:
            print(f"✗ 移动失败 {item.name}: {e}")
    if moved_count == 0:
        print("桌面已经很整洁了!没有文件需要移动。")
    else:
        print(f"\n整理完成!共移动 {moved_count} 个文件。")
if __name__ == "__main__":
    global DESKTOP
    DESKTOP = get_desktop_path()
    print(f"📁 桌面路径: {DESKTOP}")
    if not DESKTOP.exists():
        print("❌ 找不到桌面文件夹!")
        exit(1)
    create_categories()
    organize_files()

Python 版本使用方法:

  1. 保存为 organize_desktop.py
  2. 运行:
    python3 organize_desktop.py

    Windows 使用:

    python organize_desktop.py

运行效果

运行后脚本会:

  1. ✅ 自动创建分类文件夹
  2. ✅ 根据文件类型自动分类
  3. ✅ 处理重名文件(自动加序号)
  4. ✅ 显示移动进度
  5. ✅ 跳过自身和隐藏文件

提示:首次运行前建议备份重要文件,或者先在测试文件夹运行试试效果!

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