csv-stream-diff 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,114 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Iterable, Iterator, Optional, Sequence, TextIO
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class CSVOptions:
11
+ encoding: str = "utf-8-sig"
12
+ delimiter: str = ","
13
+ quotechar: str = '"'
14
+ escapechar: Optional[str] = None
15
+ newline: str = ""
16
+
17
+
18
+ def csv_kwargs(options: CSVOptions) -> dict[str, object]:
19
+ kwargs: dict[str, object] = {
20
+ "delimiter": options.delimiter,
21
+ "quotechar": options.quotechar,
22
+ }
23
+ if options.escapechar:
24
+ kwargs["escapechar"] = options.escapechar
25
+ return kwargs
26
+
27
+
28
+ def open_dict_reader(path: str | Path, options: CSVOptions) -> tuple[TextIO, csv.DictReader]:
29
+ handle = open(path, "r", encoding=options.encoding, newline=options.newline)
30
+ return handle, csv.DictReader(handle, **csv_kwargs(options))
31
+
32
+
33
+ def open_dict_writer(path: str | Path, fieldnames: Sequence[str]) -> tuple[TextIO, csv.DictWriter]:
34
+ handle = open(path, "w", encoding="utf-8", newline="")
35
+ writer = csv.DictWriter(handle, fieldnames=list(fieldnames))
36
+ writer.writeheader()
37
+ return handle, writer
38
+
39
+
40
+ def ensure_columns_exist(fieldnames: Sequence[str], required: Sequence[str], file_label: str) -> None:
41
+ missing = [column for column in required if column not in fieldnames]
42
+ if missing:
43
+ raise ValueError(f"{file_label} is missing required columns: {missing}")
44
+
45
+
46
+ def get_stream_position(handle: TextIO) -> int:
47
+ for candidate in (handle, getattr(handle, "buffer", None)):
48
+ if candidate is None:
49
+ continue
50
+ try:
51
+ return int(candidate.tell())
52
+ except (AttributeError, OSError, ValueError):
53
+ continue
54
+ return 0
55
+
56
+
57
+ def iter_csv_chunks(
58
+ path: str | Path,
59
+ options: CSVOptions,
60
+ chunk_size: int,
61
+ ) -> Iterator[tuple[list[str], list[dict[str, str]]]]:
62
+ if chunk_size <= 0:
63
+ raise ValueError("chunk_size must be greater than zero")
64
+
65
+ handle, reader = open_dict_reader(path, options)
66
+ try:
67
+ fieldnames = list(reader.fieldnames or [])
68
+ if not fieldnames:
69
+ raise ValueError(f"{path} does not contain a CSV header row")
70
+
71
+ chunk: list[dict[str, str]] = []
72
+ for row in reader:
73
+ chunk.append(row)
74
+ if len(chunk) >= chunk_size:
75
+ yield fieldnames, chunk
76
+ chunk = []
77
+ if chunk:
78
+ yield fieldnames, chunk
79
+ finally:
80
+ handle.close()
81
+
82
+
83
+ def merge_csv_parts(part_paths: Iterable[str | Path], destination: str | Path) -> int:
84
+ rows_written = 0
85
+ destination_path = Path(destination)
86
+ destination_path.parent.mkdir(parents=True, exist_ok=True)
87
+
88
+ header_written = False
89
+ writer: Optional[csv.DictWriter] = None
90
+ with open(destination_path, "w", encoding="utf-8", newline="") as destination_handle:
91
+ for part_path in part_paths:
92
+ current_path = Path(part_path)
93
+ if not current_path.exists():
94
+ continue
95
+
96
+ with open(current_path, "r", encoding="utf-8", newline="") as part_handle:
97
+ reader = csv.DictReader(part_handle)
98
+ if reader.fieldnames is None:
99
+ continue
100
+
101
+ if writer is None:
102
+ writer = csv.DictWriter(destination_handle, fieldnames=reader.fieldnames)
103
+ if not header_written:
104
+ writer.writeheader()
105
+ header_written = True
106
+
107
+ for row in reader:
108
+ writer.writerow(row)
109
+ rows_written += 1
110
+
111
+ if not header_written:
112
+ destination_path.write_text("", encoding="utf-8")
113
+
114
+ return rows_written