[分享] 一个小脚本:把杂乱的下载文件夹按「年-月」自动归档

下载文件夹越堆越乱,找东西很费劲,就写了个小脚本:按文件的修改日期,自动归档到「年-月」子文件夹。

放这里分享一下,有类似困扰的同学可以直接拿去用。

它是做什么的

  • 把散落文件按修改日期归到 2026-09、2026-08 这样的子文件夹
  • 默认只预览,不动任何文件;确认后再改一个开关真正执行
  • 遇到同名文件不覆盖,会自动加序号
  • 默认跳过隐藏文件

源码(Python 3,只用标准库,无需安装任何东西)

import os
import shutil
from datetime import datetime

DIR = r"C:\Users\你的用户名\Downloads"   # 要整理的文件夹
DRY_RUN = True                            # True=只预览;确认后改成 False
GROUP_BY = "month"                        # "month" -> 2026-09 ; "year" -> 2026
SKIP_HIDDEN = True                        # 跳过以 . 开头的隐藏文件

def target_folder(ts):
    d = datetime.fromtimestamp(ts)
    return d.strftime("%Y-%m") if GROUP_BY == "month" else d.strftime("%Y")

def main():
    if not os.path.isdir(DIR):
        print(f"[错误] 文件夹不存在:{DIR}")
        return
    moved = 0
    for name in sorted(os.listdir(DIR)):
        src = os.path.join(DIR, name)
        if not os.path.isfile(src):
            continue
        if SKIP_HIDDEN and name.startswith("."):
            continue
        folder = target_folder(os.path.getmtime(src))
        dst_dir = os.path.join(DIR, folder)
        dst = os.path.join(dst_dir, name)
        if os.path.exists(dst):                # 同名不覆盖,自动加序号
            base, ext = os.path.splitext(name)
            i = 2
            while os.path.exists(os.path.join(dst_dir, f"{base}_{i}{ext}")):
                i += 1
            dst = os.path.join(dst_dir, f"{base}_{i}{ext}")
        print(("[预览] " if DRY_RUN else "[移动] ") + f"{name}  ->  {folder}/")
        if not DRY_RUN:
            os.makedirs(dst_dir, exist_ok=True)
            shutil.move(src, dst)
        moved += 1
    print(f"\n共处理 {moved} 个文件。" + ("(当前为预览模式,未改动任何文件)" if DRY_RUN else ""))

if __name__ == "__main__":
    main()

怎么用

  1. 保存为 organize_by_date.py
  2. 把代码里的 DIR 改成你要整理的文件夹,先运行一次看预览
  3. 确认预览没问题后,把 DRY_RUN 改成 False,再运行一次

几点说明

  • 我这边只在 Windows 上实测过;macOS / Linux 理论上也能跑,但我没测
  • 移动文件不可逆,建议先拿一个小文件夹试
  • 如果你有别的整理需求(比如表格合并、重复文件查找),可以回帖说说,我看看能不能顺手加上

有 bug 或改进建议,欢迎指出。

直接上第三方资源管理器DO 可以 用各种方式分组

时间 小意思

找东西困难

直接搜索 过滤

你遇到的问题明显就不是一个 把文件移动到对应年份就能解决的

谢谢 @CallieLari,你说得在理。

DO(Directory Opus)按各种方式分组、过滤、搜索,确实比我这个几十行的小脚本强得多。如果核心诉求是「随时找得到东西」,文件管理器 + Everything 这类索引工具才是正解,这脚本替代不了。

它只想解决一个更窄的场景:一次性把散落的文件按修改时间归位,给不想装新软件、也不想做配置的人用。它不索引、也不搜索。

你提的那点我认,所以按这个思路把它改了(v2):

  1. --by-type:归档后再按类型分一层(图片 / 视频 / 文档 / 音频 / 压缩包 / 安装包 / 代码 / 其他);
  2. --find-dupes:先扫出内容相同的重复文件并打印清单(只读,不删除任何文件);
  3. 参数改成命令行开关,不用再改源码;默认仍是「只预览、不动文件」。

对 DO 用户来说它确实没用,这点我同意——它只服务想「搬一次家」的人。

右键-分组依据-修改日期

有可能有些用户更不想安装python :rofl:

那么可以试试菲菲更名宝贝。

以后这种低频次的,比较小众的,一次性的操作,可能会更多的依赖AI来完成更加方便了。
这个活对现在的AI来说,简直是简单的不能再简单了。

Python 还是有点重了,毕竟不是所有电脑都预装了 Python 环境。个人建议是:

  • Windows 上,用 Powershell(或更轻一点,用 cmd)
  • Linux、macOS 和 BSD 上,用 POSIX Shell 配合 coreunits

@VictoryRoad 这个建议说到点子上了。Windows 上 PowerShell 确实是更合理的载体——系统自带、不用装任何东西。我把 v2 完整移植成了 PowerShell 版(功能对齐:预览/执行/-ByType/-FindDupes),如下:

<#
  按修改日期整理文件 · PowerShell 零依赖版(Windows 8/10/11 自带 PowerShell 可直接运行)
  用法:
    .\按日期整理文件.ps1 -Dir "C:\Users\me\Downloads"              # 预览(不动文件)
    .\按日期整理文件.ps1 -Dir "C:\Users\me\Downloads" -Apply       # 真正执行
    .\按日期整理文件.ps1 -Dir "..." -Apply -ByType                 # 再按类型分层
    .\按日期整理文件.ps1 -Dir "..." -FindDupes                     # 只找重复文件
#>
param(
    [string]$Dir = ".",
    [switch]$Apply,
    [switch]$ByType,
    [switch]$FindDupes
)

$ErrorActionPreference = "Stop"
$root = (Resolve-Path -LiteralPath $Dir).Path

$TYPE_MAP = [ordered]@{
    "图片"   = ".jpg .jpeg .png .gif .bmp .webp .heic .heif .tif .tiff .raw .svg .ico .avif"
    "视频"   = ".mp4 .mkv .mov .avi .wmv .flv .webm .m4v .ts .rmvb"
    "音频"   = ".mp3 .wav .flac .aac .m4a .ogg .wma .ape"
    "文档"   = ".pdf .doc .docx .xls .xlsx .ppt .pptx .txt .md .rtf .csv .odt .ods .odp .epub .mobi"
    "压缩包" = ".zip .rar .7z .tar .gz .bz2 .xz .iso"
    "安装包" = ".exe .msi .dmg .pkg .deb .rpm .apk .appx"
    "代码"   = ".py .js .ts .java .c .cpp .h .cs .go .rs .php .rb .sh .bat .ps1 .sql .json .xml .yml .yaml .html .css"
}

function Get-TypeGroup([string]$name) {
    $ext = [IO.Path]::GetExtension($name).ToLower()
    foreach ($k in $TYPE_MAP.Keys) {
        if ($TYPE_MAP[$k].Split(" ") -contains $ext) { return $k }
    }
    return "其他"
}

function Get-UniquePath([string]$target) {
    if (-not (Test-Path -LiteralPath $target)) { return $target }
    $dir = Split-Path $target -Parent
    $stem = [IO.Path]::GetFileNameWithoutExtension($target)
    $ext = [IO.Path]::GetExtension($target)
    $n = 2
    while (Test-Path -LiteralPath (Join-Path $dir ("{0}_{1}{2}" -f $stem, $n, $ext))) { $n++ }
    return Join-Path $dir ("{0}_{1}{2}" -f $stem, $n, $ext)
}

$files = @(Get-ChildItem -LiteralPath $root -File | Where-Object {
    -not $_.Attributes.HasFlag([IO.FileAttributes]::Hidden) -and
    -not $_.Attributes.HasFlag([IO.FileAttributes]::System)
})

if ($FindDupes) {
    $groups = @{}
    foreach ($f in $files) {
        $h = (Get-FileHash -LiteralPath $f.FullName -Algorithm MD5).Hash
        if (-not $groups.ContainsKey($h)) { $groups[$h] = New-Object System.Collections.ArrayList }
        [void]$groups[$h].Add($f.FullName)
    }
    $dupCount = 0
    foreach ($h in $groups.Keys) {
        if ($groups[$h].Count -gt 1) {
            $dupCount++
            Write-Output ("重复组 {0}:" -f $dupCount)
            foreach ($p in $groups[$h]) { Write-Output ("    " + $p) }
        }
    }
    if ($dupCount -eq 0) { Write-Output "没有发现内容相同的重复文件。" }
    return
}

$plan = @()
foreach ($f in $files) {
    $m = $f.LastWriteTime
    $sub = "{0:D4}-{1:D2}" -f $m.Year, $m.Month
    if ($ByType) { $sub = Join-Path $sub (Get-TypeGroup $f.Name) }
    $target = Join-Path (Join-Path $root $sub) $f.Name
    $plan += [pscustomobject]@{ File = $f; Target = (Get-UniquePath $target) }
}

if ($plan.Count -eq 0) { Write-Output "没有可整理的文件。"; return }

if (-not $Apply) {
    Write-Output ("【预览模式】共 {0} 个文件将被归档(未做任何改动;加 -Apply 执行):" -f $plan.Count)
    foreach ($p in $plan) {
        Write-Output ("    {0}  ->  {1}" -f $p.File.Name, $p.Target.Substring($root.Length + 1))
    }
    return
}

$moved = 0
foreach ($p in $plan) {
    $tdir = Split-Path $p.Target -Parent
    if (-not (Test-Path -LiteralPath $tdir)) {
        New-Item -ItemType Directory -Path $tdir -Force | Out-Null
    }
    Move-Item -LiteralPath $p.File.FullName -Destination $p.Target
    $moved++
    Write-Output ("已移动  {0}  ->  {1}" -f $p.File.Name, $p.Target.Substring($root.Length + 1))
}
Write-Output ("完成:共移动 {0} 个文件。" -f $moved)

发布前自测记录(Windows PowerShell 5.1,14 项断言全过):

  1. 预览模式:只打印计划,夹具 5 个文件未移动;
  2. Apply:2026-09\a.pdf、2026-08\b.txt、2025-12\c.jpg 结构正确;
  3. 同名冲突:归档后同月再来一个同名新文件,二次执行自动存为 a_2.pdf,原文件内容 MD5 不变;
  4. 文件总数守恒(无丢失无复制);
  5. -ByType 两层结构(2026-09\文档\a.pdf)正确;
  6. -FindDupes 列出重复组且不动文件;
  7. 空文件夹友好提示。

两个诚实的说明:

  • 保存时请把文件存成「UTF-8 with BOM」编码(记事本另存为选 UTF-8 即可),否则 Windows PowerShell 5.1 会把中文注释读成乱码——类型分组名(图片/视频/文档…)会受影响。这是我自测时自己踩到的坑,一并写出来;
  • 这个版本只面向 Windows。Linux/macOS 的情况和 Windows 不同(POSIX shell 处理文件名空格/特殊字符要格外小心,mv 的批量行为也和 PowerShell 不一样),暂不提供半成品,Python 版依然是跨平台的选项。

@dangerace 说得对,这类一次性小活 AI 确实张口就来——所以我把自测也一起交了,至少能对上"能用"这两个字。