Inbox zero для папки
Показывает файлы из папки входящих и по команде раскладывает их по архиву месяцев.
Что делает скрипт
По умолчанию скрипт только показывает файлы, их возраст и размер. С флагом apply он перемещает выбранные файлы в архив с подпапкой по месяцу, не удаляя и не перезаписывая данные. Конфликты имён решаются добавлением числового суффикса.
- Перемещение выполняется только с --apply. Проверьте список до запуска.
Быстрый старт
python inbox_zero.py --path ~/Downloads
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python inbox_zero.py --path ~/Downloadspython inbox_zero.py --path ~/Downloads --older-than 30python inbox_zero.py --path ~/Downloads --apply --archive ~/Archive
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
inbox_zero.py
#!/usr/bin/env python3
"""Разбор папки входящих с перемещением в архив по месяцам."""
from __future__ import annotations
import argparse
import json
import shutil
from datetime import date, datetime
from pathlib import Path
def unique_target(directory: Path, name: str) -> Path:
target = directory / name
if not target.exists():
return target
stem = target.stem
suffix = target.suffix
counter = 1
while True:
candidate = directory / f"{stem}-{counter}{suffix}"
if not candidate.exists():
return candidate
counter += 1
def main() -> int:
parser = argparse.ArgumentParser(description="Inbox zero для папки")
parser.add_argument("--path", type=Path, required=True, help="Папка входящих")
parser.add_argument("--archive", type=Path, help="Корень архива")
parser.add_argument("--older-than", type=int, default=0, help="Минимальный возраст файла в днях")
parser.add_argument("--apply", action="store_true", help="Выполнить перемещение")
parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
parser.add_argument("--force", action="store_true")
args = parser.parse_args()
source = args.path.expanduser().resolve()
if not source.is_dir():
parser.error(f"Папка не найдена: {source}")
if args.older_than < 0:
parser.error("--older-than не может быть отрицательным")
archive = args.archive.expanduser().resolve() if args.archive else source.parent / "archive"
today = date.today()
files = [item for item in source.iterdir() if item.is_file() and not item.is_symlink()]
files.sort(key=lambda item: item.stat().st_mtime)
candidates = []
for item in files:
modified = datetime.fromtimestamp(item.stat().st_mtime)
age = (today - modified.date()).days
if age < args.older_than:
continue
candidates.append({"path": item, "age": age, "size": item.stat().st_size, "modified": modified})
if not candidates:
print("Файлов для разбора нет.")
return 0
print(f"{'Файл':40} {'Дней':>6} {'КБ':>10} {'Изменён':16}")
for item in candidates:
print(
f"{item['path'].name[:40]:40} {item['age']:>6} "
f"{item['size'] / 1024:>10.1f} {item['modified'].strftime('%Y-%m-%d %H:%M')}"
)
moved = []
if args.apply:
for item in candidates:
month = item["modified"].strftime("%Y-%m")
destination_dir = archive / month
destination_dir.mkdir(parents=True, exist_ok=True)
target = unique_target(destination_dir, item["path"].name)
shutil.move(str(item["path"]), str(target))
moved.append({"from": str(item["path"]), "to": str(target)})
print(f"Перемещено: {item['path'].name} -> {target}")
print(f"Всего перемещено: {len(moved)}")
else:
print("Это предпросмотр. Для перемещения добавьте --apply.")
if args.json:
output = args.json.expanduser()
if output.exists() and not args.force:
parser.error(f"Файл уже существует: {output}. Добавьте --force.")
output.parent.mkdir(parents=True, exist_ok=True)
report = {
"source": str(source),
"archive": str(archive),
"applied": bool(args.apply),
"files": [
{
"name": item["path"].name,
"age_days": item["age"],
"size": item["size"],
"modified": item["modified"].isoformat(),
}
for item in candidates
],
"moved": moved,
}
output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Отчёт сохранён: {output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.