#!/usr/bin/env python3 """Сортировка CSV по нескольким колонкам.""" from __future__ import annotations import argparse import csv from pathlib import Path def sort_key(row: dict[str, str], columns: list[str], numeric: set[str]): parts = [] for column in columns: value = (row.get(column) or "").strip() if column in numeric: if value == "": parts.append((1, 0.0)) else: try: parts.append((0, float(value))) except ValueError: parts.append((2, 0.0)) else: parts.append((1, "") if value == "" else (0, value.casefold())) return tuple(parts) def main() -> int: parser = argparse.ArgumentParser(description="Сортировка CSV") parser.add_argument("--input", type=Path, required=True, help="Исходный CSV") parser.add_argument("--output", type=Path, default=Path("sorted.csv"), help="Результат") parser.add_argument("--by", required=True, help="Колонки сортировки через запятую") parser.add_argument("--numeric", default="", help="Числовые колонки через запятую") parser.add_argument("--desc", action="store_true", help="Обратный порядок") parser.add_argument("--delimiter", default=",", help="Разделитель колонок") parser.add_argument("--force", action="store_true", help="Перезаписать выходной файл") args = parser.parse_args() source = args.input.expanduser().resolve() target = args.output.expanduser().resolve() if not source.is_file(): parser.error(f"Файл не найден: {source}") if source == target: parser.error("Выходной файл не должен совпадать с исходным") if target.exists() and not args.force: parser.error(f"Файл уже существует: {target}. Добавьте --force") if len(args.delimiter) != 1: parser.error("Разделитель должен состоять из одного символа") columns = [item.strip() for item in args.by.split(",") if item.strip()] numeric = {item.strip() for item in args.numeric.split(",") if item.strip()} if not columns: parser.error("Укажите хотя бы одну колонку в --by") with source.open("r", encoding="utf-8-sig", newline="") as handle: reader = csv.DictReader(handle, delimiter=args.delimiter) if reader.fieldnames is None: parser.error("Не удалось прочитать заголовок") missing = [name for name in columns if name not in reader.fieldnames] if missing: parser.error("Нет колонок: " + ", ".join(missing)) rows = list(reader) rows.sort(key=lambda row: sort_key(row, columns, numeric), reverse=args.desc) with target.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=reader.fieldnames, delimiter=args.delimiter, lineterminator="\n") writer.writeheader() writer.writerows(rows) print(f"Строк: {len(rows)}") print(f"Сортировка: {', '.join(columns)}") print(f"Результат: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())