#!/usr/bin/env python3 """Разбиение CSV на части с повторением заголовка.""" from __future__ import annotations import argparse import csv import math from pathlib import Path def main() -> int: parser = argparse.ArgumentParser(description="Разбить CSV на части") parser.add_argument("--input", type=Path, required=True, help="Исходный CSV") parser.add_argument("--out-dir", type=Path, default=Path("split"), help="Папка для частей") parser.add_argument("--rows", type=int, default=1000, help="Строк данных в одном файле") parser.add_argument("--prefix", default="", help="Префикс имён файлов") parser.add_argument("--delimiter", default=",", help="Разделитель колонок") parser.add_argument("--force", action="store_true", help="Перезаписать существующие части") args = parser.parse_args() source = args.input.expanduser().resolve() if not source.is_file(): parser.error(f"Файл не найден: {source}") if args.rows < 1: parser.error("--rows должен быть больше нуля") if len(args.delimiter) != 1: parser.error("Разделитель должен состоять из одного символа") out_dir = args.out_dir.expanduser().resolve() prefix = args.prefix or source.stem 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("Исходный файл пуст") total = sum(1 for _ in reader) if total == 0: parser.error("В файле нет строк данных") parts = math.ceil(total / args.rows) targets = [out_dir / f"{prefix}_part_{index:03d}.csv" for index in range(1, parts + 1)] existing = [path for path in targets if path.exists()] if existing and not args.force: parser.error("Уже существуют файлы: " + ", ".join(str(path) for path in existing[:3])) out_dir.mkdir(parents=True, exist_ok=True) written = 0 with source.open("r", encoding="utf-8-sig", newline="") as handle: reader = csv.reader(handle, delimiter=args.delimiter) next(reader) for part_index, target in enumerate(targets, start=1): with target.open("w", encoding="utf-8", newline="") as output: writer = csv.writer(output, delimiter=args.delimiter, lineterminator="\n") writer.writerow(header) for _ in range(args.rows): try: row = next(reader) except StopIteration: break writer.writerow(row) written += 1 print(f"Строк данных: {total}") print(f"Частей: {parts}") print(f"Записано строк: {written}") print(f"Папка: {out_dir}") return 0 if __name__ == "__main__": raise SystemExit(main())