Каталог музыки по тегам
Читает исполнителя, альбом, год и жанр через mutagen и собирает CSV по всей коллекции.
Что делает скрипт
Скрипт проходит по аудиофайлам, подставляет пустые значения и показывает длительность. Отдельно считаются треки без обязательных тегов. Оригиналы не меняются, отчёт удобно открыть в таблице.
Быстрый старт
python music_catalog.py --dir ~/Music --csv music.csv
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python music_catalog.py --dir ~/Musicpython music_catalog.py --dir ~/Music --csv music.csvpython music_catalog.py --dir D:\Music --json music.json
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
py -m pip install mutagen
python3 -m pip install mutagen
python3 -m pip install mutagen
music_catalog.py
#!/usr/bin/env python3
"""Собирает каталог музыки по тегам."""
from __future__ import annotations
import argparse
import csv
import json
from pathlib import Path
from mutagen import File as MutagenFile
AUDIO_EXTENSIONS = {".mp3", ".flac", ".m4a", ".ogg", ".opus", ".wav"}
def first(tags, key: str) -> str:
value = tags.get(key)
if isinstance(value, list):
value = value[0] if value else ""
return "" if value is None else str(value).strip()
def main() -> int:
parser = argparse.ArgumentParser(description="Каталог музыки")
parser.add_argument("--dir", type=Path, required=True, help="Папка с музыкой")
parser.add_argument("--csv", type=Path, help="Сохранить CSV")
parser.add_argument("--json", type=Path, help="Сохранить JSON")
args = parser.parse_args()
root = args.dir.expanduser().resolve()
if not root.is_dir():
parser.error(f"Папка не найдена: {root}")
rows = []
incomplete = 0
for path in sorted(root.rglob("*")):
if not path.is_file() or path.suffix.lower() not in AUDIO_EXTENSIONS:
continue
try:
audio = MutagenFile(path, easy=True)
except Exception as error:
print(f"Не прочитано: {path}: {error}")
continue
if audio is None:
continue
tags = audio.tags or {}
artist = first(tags, "artist")
album = first(tags, "album")
title = first(tags, "title")
if not artist or not album or not title:
incomplete += 1
duration = float(getattr(audio.info, "length", 0.0))
rows.append(
{
"artist": artist,
"album": album,
"title": title,
"track": first(tags, "track"),
"year": first(tags, "date")[:4],
"genre": first(tags, "genre"),
"duration": round(duration, 1),
"file": str(path.relative_to(root)),
}
)
if not rows:
print("Аудиофайлы не найдены.")
return 1
for row in rows[:25]:
print(f"{row['artist'] or '?'} - {row['album'] or '?'} - {row['title'] or '?'}")
if len(rows) > 25:
print(f"И ещё {len(rows) - 25} записей.")
if args.csv:
target = args.csv.expanduser()
target.parent.mkdir(parents=True, exist_ok=True)
with target.open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
print(f"CSV: {target}")
if args.json:
target = args.json.expanduser()
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(rows, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"JSON: {target}")
print(f"Треков: {len(rows)}, без части тегов: {incomplete}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.