#!/usr/bin/env python3 """Переименование колонок CSV по карте.""" from __future__ import annotations import argparse import csv import json import re from pathlib import Path def normalize_header(name: str, index: int, seen: set[str]) -> str: value = name.replace("\ufeff", "").strip().lower() value = re.sub(r"[^\w]+", "_", value, flags=re.UNICODE).strip("_") if not value: value = f"column_{index}" base = value counter = 2 while value in seen: value = f"{base}_{counter}" counter += 1 seen.add(value) return value 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("renamed.csv"), help="Результат") parser.add_argument("--map", action="append", default=[], help="Пара old=new, можно повторять") parser.add_argument("--mapping-json", type=Path, help="JSON-файл с объектом old: new") parser.add_argument("--normalize", action="store_true", help="Нормализовать все заголовки") parser.add_argument("--ignore-missing", 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("Разделитель должен состоять из одного символа") mapping: dict[str, str] = {} if args.mapping_json: try: loaded = json.loads(args.mapping_json.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as error: parser.error(f"Не удалось прочитать JSON: {error}") if not isinstance(loaded, dict) or any(not isinstance(key, str) or not isinstance(value, str) for key, value in loaded.items()): parser.error("JSON должен содержать объект строка-строка") mapping.update(loaded) for item in args.map: if "=" not in item: parser.error(f"Ожидается old=new: {item}") old, new = item.split("=", 1) old, new = old.strip(), new.strip() if not old or not new: parser.error(f"Пустое имя в паре: {item}") mapping[old] = new with source.open("r", encoding="utf-8-sig", newline="") as handle: reader = csv.reader(handle, delimiter=args.delimiter) try: header = next(reader) except StopIteration: parser.error("Исходный файл пуст") rows = list(reader) missing = [name for name in mapping if name not in header] if missing and not args.ignore_missing: parser.error("Нет колонок: " + ", ".join(missing)) renamed = [mapping.get(name, name) for name in header] if args.normalize: seen: set[str] = set() renamed = [normalize_header(name, index + 1, seen) for index, name in enumerate(renamed)] duplicates = sorted({name for name in renamed if renamed.count(name) > 1}) if duplicates: parser.error("Повторяющиеся имена после переименования: " + ", ".join(duplicates)) with target.open("w", encoding="utf-8", newline="") as handle: writer = csv.writer(handle, delimiter=args.delimiter, lineterminator="\n") writer.writerow(renamed) writer.writerows(rows) changed = sum(1 for old, new in zip(header, renamed) if old != new) print(f"Колонок: {len(renamed)}") print(f"Переименовано: {changed}") print(f"Результат: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())