| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
Wrappers for some loading/saving functionality. |
| 5 |
|
| 6 |
Author: Gertjan van den Burg |
| 7 |
|
| 8 |
""" |
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import os |
| 12 |
import warnings |
| 13 |
|
| 14 |
from typing import TYPE_CHECKING |
| 15 |
from typing import Any |
| 16 |
from typing import Iterable |
| 17 |
from typing import Iterator |
| 18 |
from typing import List |
| 19 |
from typing import Mapping |
| 20 |
from typing import Optional |
| 21 |
from typing import TypeVar |
| 22 |
|
| 23 |
from ._optional import import_optional_dependency |
| 24 |
from .detect import Detector |
| 25 |
from .dialect import SimpleDialect |
| 26 |
from .dict_read_write import DictReader |
| 27 |
from .dict_read_write import DictWriter |
| 28 |
from .encoding import get_encoding |
| 29 |
from .exceptions import NoDetectionResult |
| 30 |
from .read import reader |
| 31 |
from .write import writer |
| 32 |
|
| 33 |
if TYPE_CHECKING: |
| 34 |
import pandas as pd |
| 35 |
|
| 36 |
from ._types import FileDescriptorOrPath |
| 37 |
from ._types import _DialectLike |
| 38 |
from ._types import _DictReadMapping |
| 39 |
|
| 40 |
_T = TypeVar("_T") |
| 41 |
|
| 42 |
|
| 43 |
def stream_dicts( |
| 44 |
filename: FileDescriptorOrPath, |
| 45 |
dialect: Optional[_DialectLike] = None, |
| 46 |
encoding: Optional[str] = None, |
| 47 |
num_chars: Optional[int] = None, |
| 48 |
verbose: bool = False, |
| 49 |
) -> Iterator["_DictReadMapping"]: |
| 50 |
"""Read a CSV file as a generator over dictionaries |
| 51 |
|
| 52 |
This function streams the rows of the CSV file as dictionaries. The keys of |
| 53 |
the dictionaries are assumed to be in the first row of the CSV file. The |
| 54 |
dialect will be detected automatically, unless it is provided. |
| 55 |
|
| 56 |
Parameters |
| 57 |
---------- |
| 58 |
filename : str |
| 59 |
Path of the CSV file |
| 60 |
|
| 61 |
dialect : str, SimpleDialect, or csv.Dialect object |
| 62 |
If the dialect is known, it can be provided here. This function uses |
| 63 |
the Clevercsv :class:`clevercsv.DictReader` object, which supports |
| 64 |
various dialect types (string, SimpleDialect, or csv.Dialect). If None, |
| 65 |
the dialect will be detected. |
| 66 |
|
| 67 |
encoding : str |
| 68 |
The encoding of the file. If None, it is detected. |
| 69 |
|
| 70 |
num_chars : int |
| 71 |
Number of characters to use to detect the dialect. If None, use the |
| 72 |
entire file. |
| 73 |
|
| 74 |
Note that using less than the entire file will speed up detection, but |
| 75 |
can reduce the accuracy of the detected dialect. |
| 76 |
|
| 77 |
verbose: bool |
| 78 |
Whether or not to show detection progress. |
| 79 |
|
| 80 |
Returns |
| 81 |
------- |
| 82 |
rows: generator |
| 83 |
Returns file as a generator over rows as dictionaries. |
| 84 |
|
| 85 |
Raises |
| 86 |
------ |
| 87 |
NoDetectionResult |
| 88 |
When the dialect detection fails. |
| 89 |
|
| 90 |
""" |
| 91 |
if encoding is None: |
| 92 |
encoding = get_encoding(filename) |
| 93 |
with open(filename, "r", newline="", encoding=encoding) as fid: |
| 94 |
if dialect is None: |
| 95 |
data = fid.read(num_chars) if num_chars else fid.read() |
| 96 |
dialect = Detector().detect(data, verbose=verbose) |
| 97 |
fid.seek(0) |
| 98 |
|
| 99 |
if dialect is None: |
| 100 |
raise NoDetectionResult |
| 101 |
|
| 102 |
reader: DictReader = DictReader(fid, dialect=dialect) |
| 103 |
for row in reader: |
| 104 |
yield row |
| 105 |
|
| 106 |
|
| 107 |
def read_dicts( |
| 108 |
filename: "FileDescriptorOrPath", |
| 109 |
dialect: Optional["_DialectLike"] = None, |
| 110 |
encoding: Optional[str] = None, |
| 111 |
num_chars: Optional[int] = None, |
| 112 |
verbose: bool = False, |
| 113 |
) -> List["_DictReadMapping"]: |
| 114 |
"""Read a CSV file as a list of dictionaries |
| 115 |
|
| 116 |
This function returns the rows of the CSV file as a list of dictionaries. |
| 117 |
The keys of the dictionaries are assumed to be in the first row of the CSV |
| 118 |
file. The dialect will be detected automatically, unless it is provided. |
| 119 |
|
| 120 |
Parameters |
| 121 |
---------- |
| 122 |
filename : str |
| 123 |
Path of the CSV file |
| 124 |
|
| 125 |
dialect : str, SimpleDialect, or csv.Dialect object |
| 126 |
If the dialect is known, it can be provided here. This function uses |
| 127 |
the Clevercsv :class:`clevercsv.DictReader` object, which supports |
| 128 |
various dialect types (string, SimpleDialect, or csv.Dialect). If None, |
| 129 |
the dialect will be detected. |
| 130 |
|
| 131 |
encoding : str |
| 132 |
The encoding of the file. If None, it is detected. |
| 133 |
|
| 134 |
num_chars : int |
| 135 |
Number of characters to use to detect the dialect. If None, use the |
| 136 |
entire file. |
| 137 |
|
| 138 |
Note that using less than the entire file will speed up detection, but |
| 139 |
can reduce the accuracy of the detected dialect. |
| 140 |
|
| 141 |
verbose: bool |
| 142 |
Whether or not to show detection progress. |
| 143 |
|
| 144 |
Returns |
| 145 |
------- |
| 146 |
rows: list |
| 147 |
Returns rows of the file as a list of dictionaries. |
| 148 |
|
| 149 |
Raises |
| 150 |
------ |
| 151 |
NoDetectionResult |
| 152 |
When the dialect detection fails. |
| 153 |
|
| 154 |
""" |
| 155 |
return list( |
| 156 |
stream_dicts( |
| 157 |
filename, |
| 158 |
dialect=dialect, |
| 159 |
encoding=encoding, |
| 160 |
num_chars=num_chars, |
| 161 |
verbose=verbose, |
| 162 |
) |
| 163 |
) |
| 164 |
|
| 165 |
|
| 166 |
def read_table( |
| 167 |
filename: "FileDescriptorOrPath", |
| 168 |
dialect: Optional["_DialectLike"] = None, |
| 169 |
encoding: Optional[str] = None, |
| 170 |
num_chars: Optional[int] = None, |
| 171 |
verbose: bool = False, |
| 172 |
) -> List[List[str]]: |
| 173 |
"""Read a CSV file as a table (a list of lists) |
| 174 |
|
| 175 |
This is a convenience function that reads a CSV file and returns the data |
| 176 |
as a list of lists (= rows). The dialect will be detected automatically, |
| 177 |
unless it is provided. |
| 178 |
|
| 179 |
Parameters |
| 180 |
---------- |
| 181 |
filename: str |
| 182 |
Path of the CSV file |
| 183 |
|
| 184 |
dialect: str, SimpleDialect, or csv.Dialect object |
| 185 |
If the dialect is known, it can be provided here. This function uses |
| 186 |
the CleverCSV :class:`clevercsv.reader` object, which supports various |
| 187 |
dialect types (string, SimpleDialect, or csv.Dialect). If None, the |
| 188 |
dialect will be detected. |
| 189 |
|
| 190 |
encoding : str |
| 191 |
The encoding of the file. If None, it is detected. |
| 192 |
|
| 193 |
num_chars : int |
| 194 |
Number of characters to use to detect the dialect. If None, use the |
| 195 |
entire file. |
| 196 |
|
| 197 |
Note that using less than the entire file will speed up detection, but |
| 198 |
can reduce the accuracy of the detected dialect. |
| 199 |
|
| 200 |
verbose: bool |
| 201 |
Whether or not to show detection progress. |
| 202 |
|
| 203 |
Returns |
| 204 |
------- |
| 205 |
rows: list |
| 206 |
Returns rows as a list of lists. |
| 207 |
|
| 208 |
Raises |
| 209 |
------ |
| 210 |
NoDetectionResult |
| 211 |
When the dialect detection fails. |
| 212 |
|
| 213 |
""" |
| 214 |
return list( |
| 215 |
stream_table( |
| 216 |
filename, |
| 217 |
dialect=dialect, |
| 218 |
encoding=encoding, |
| 219 |
num_chars=num_chars, |
| 220 |
verbose=verbose, |
| 221 |
) |
| 222 |
) |
| 223 |
|
| 224 |
|
| 225 |
def stream_table( |
| 226 |
filename: "FileDescriptorOrPath", |
| 227 |
dialect: Optional["_DialectLike"] = None, |
| 228 |
encoding: Optional[str] = None, |
| 229 |
num_chars: Optional[int] = None, |
| 230 |
verbose: bool = False, |
| 231 |
) -> Iterator[List[str]]: |
| 232 |
"""Read a CSV file as a generator over rows of a table |
| 233 |
|
| 234 |
This is a convenience function that reads a CSV file and returns the data |
| 235 |
as a generator of rows. The dialect will be detected automatically, unless |
| 236 |
it is provided. |
| 237 |
|
| 238 |
Parameters |
| 239 |
---------- |
| 240 |
filename: str |
| 241 |
Path of the CSV file |
| 242 |
|
| 243 |
dialect: str, SimpleDialect, or csv.Dialect object |
| 244 |
If the dialect is known, it can be provided here. This function uses |
| 245 |
the CleverCSV :class:`clevercsv.reader` object, which supports various |
| 246 |
dialect types (string, SimpleDialect, or csv.Dialect). If None, the |
| 247 |
dialect will be detected. |
| 248 |
|
| 249 |
encoding : str |
| 250 |
The encoding of the file. If None, it is detected. |
| 251 |
|
| 252 |
num_chars : int |
| 253 |
Number of characters to use to detect the dialect. If None, use the |
| 254 |
entire file. |
| 255 |
|
| 256 |
Note that using less than the entire file will speed up detection, but |
| 257 |
can reduce the accuracy of the detected dialect. |
| 258 |
|
| 259 |
verbose: bool |
| 260 |
Whether or not to show detection progress. |
| 261 |
|
| 262 |
Returns |
| 263 |
------- |
| 264 |
rows: generator |
| 265 |
Returns file as a generator over rows. |
| 266 |
|
| 267 |
Raises |
| 268 |
------ |
| 269 |
NoDetectionResult |
| 270 |
When the dialect detection fails. |
| 271 |
|
| 272 |
""" |
| 273 |
if encoding is None: |
| 274 |
encoding = get_encoding(filename) |
| 275 |
with open(filename, "r", newline="", encoding=encoding) as fid: |
| 276 |
if dialect is None: |
| 277 |
data = fid.read(num_chars) if num_chars else fid.read() |
| 278 |
dialect = Detector().detect(data, verbose=verbose) |
| 279 |
if dialect is None: |
| 280 |
raise NoDetectionResult() |
| 281 |
fid.seek(0) |
| 282 |
r = reader(fid, dialect) |
| 283 |
yield from r |
| 284 |
|
| 285 |
|
| 286 |
def read_dataframe( |
| 287 |
filename: "FileDescriptorOrPath", |
| 288 |
*args: Any, |
| 289 |
num_chars: Optional[int] = None, |
| 290 |
**kwargs: Any, |
| 291 |
) -> pd.DataFrame: |
| 292 |
"""Read a CSV file to a Pandas dataframe |
| 293 |
|
| 294 |
This function uses CleverCSV to detect the dialect, and then passes this to |
| 295 |
the ``read_csv`` function in pandas. Additional arguments and keyword |
| 296 |
arguments are passed to ``read_csv`` as well. |
| 297 |
|
| 298 |
Parameters |
| 299 |
---------- |
| 300 |
|
| 301 |
filename: str |
| 302 |
The filename of the CSV file. At the moment, only local files are |
| 303 |
supported. |
| 304 |
|
| 305 |
*args: |
| 306 |
Additional arguments for the ``pandas.read_csv`` function. |
| 307 |
|
| 308 |
num_chars: int |
| 309 |
Number of characters to use for dialect detection. If None, use the |
| 310 |
entire file. |
| 311 |
|
| 312 |
Note that using less than the entire file will speed up detection, but |
| 313 |
can reduce the accuracy of the detected dialect. |
| 314 |
|
| 315 |
**kwargs: |
| 316 |
Additional keyword arguments for the ``pandas.read_csv`` function. You |
| 317 |
can specify the file encoding here if needed, and it will be used |
| 318 |
during dialect detection. |
| 319 |
|
| 320 |
""" |
| 321 |
if not (os.path.exists(filename) and os.path.isfile(filename)): |
| 322 |
raise ValueError("Filename must be a regular file") |
| 323 |
pd = import_optional_dependency("pandas") |
| 324 |
assert pd is not None |
| 325 |
|
| 326 |
|
| 327 |
enc = kwargs.get("encoding") or get_encoding(filename) |
| 328 |
kwargs["encoding"] = enc |
| 329 |
|
| 330 |
with open(filename, "r", newline="", encoding=enc) as fid: |
| 331 |
data = fid.read(num_chars) if num_chars else fid.read() |
| 332 |
dialect = Detector().detect(data) |
| 333 |
|
| 334 |
if dialect is None: |
| 335 |
raise NoDetectionResult |
| 336 |
|
| 337 |
csv_dialect = dialect.to_csv_dialect() |
| 338 |
|
| 339 |
|
| 340 |
with warnings.catch_warnings(): |
| 341 |
warnings.filterwarnings( |
| 342 |
"ignore", |
| 343 |
message="^Conflicting values for .*", |
| 344 |
category=pd.errors.ParserWarning, |
| 345 |
) |
| 346 |
df = pd.read_csv(filename, *args, dialect=csv_dialect, **kwargs) |
| 347 |
return df |
| 348 |
|
| 349 |
|
| 350 |
def detect_dialect( |
| 351 |
filename: "FileDescriptorOrPath", |
| 352 |
num_chars: Optional[int] = None, |
| 353 |
encoding: Optional[str] = None, |
| 354 |
verbose: bool = False, |
| 355 |
method: str = "auto", |
| 356 |
skip: bool = True, |
| 357 |
) -> Optional[SimpleDialect]: |
| 358 |
"""Detect the dialect of a CSV file |
| 359 |
|
| 360 |
This is a utility function that simply returns the detected dialect of a |
| 361 |
given CSV file. |
| 362 |
|
| 363 |
Parameters |
| 364 |
---------- |
| 365 |
filename : str |
| 366 |
The filename of the CSV file. |
| 367 |
|
| 368 |
num_chars : int |
| 369 |
Number of characters to read for the detection. If None, the entire |
| 370 |
file will be read. Note that limiting the number of characters can |
| 371 |
reduce the accuracy of the detected dialect. |
| 372 |
|
| 373 |
encoding : str |
| 374 |
The file encoding of the CSV file. If None, it is detected. |
| 375 |
|
| 376 |
verbose : bool |
| 377 |
Enable verbose mode during detection. |
| 378 |
|
| 379 |
method : str |
| 380 |
Dialect detection method to use. Either 'normal' for normal form |
| 381 |
detection, 'consistency' for the consistency measure, or 'auto' for |
| 382 |
first normal and then consistency. |
| 383 |
|
| 384 |
skip : bool |
| 385 |
Skip computation of the type score for dialects with a low pattern |
| 386 |
score. |
| 387 |
|
| 388 |
Returns |
| 389 |
------- |
| 390 |
dialect : Optional[SimpleDialect] |
| 391 |
The detected dialect as a :class:`SimpleDialect`, or None if detection |
| 392 |
failed. |
| 393 |
|
| 394 |
""" |
| 395 |
enc = encoding or get_encoding(filename) |
| 396 |
with open(filename, "r", newline="", encoding=enc) as fp: |
| 397 |
data = fp.read(num_chars) if num_chars else fp.read() |
| 398 |
dialect = Detector().detect( |
| 399 |
data, verbose=verbose, method=method, skip=skip |
| 400 |
) |
| 401 |
return dialect |
| 402 |
|
| 403 |
|
| 404 |
def write_table( |
| 405 |
table: Iterable[Iterable[Any]], |
| 406 |
filename: "FileDescriptorOrPath", |
| 407 |
dialect: "_DialectLike" = "excel", |
| 408 |
transpose: bool = False, |
| 409 |
encoding: Optional[str] = None, |
| 410 |
) -> None: |
| 411 |
"""Write a table (a list of lists) to a file |
| 412 |
|
| 413 |
This is a convenience function for writing a table to a CSV file. If the |
| 414 |
table has no rows, no output file is created. |
| 415 |
|
| 416 |
Parameters |
| 417 |
---------- |
| 418 |
table : list |
| 419 |
A table as a list of lists. The table must have the same number of |
| 420 |
cells in each row (taking the :attr:`transpose` flag into account). |
| 421 |
|
| 422 |
filename : str |
| 423 |
The filename of the CSV file to write the table to. |
| 424 |
|
| 425 |
dialect : SimpleDialect or csv.Dialect |
| 426 |
The dialect to use. The default is the 'excel' dialect, which |
| 427 |
corresponds to RFC4180. This is done to encourage more standardized CSV |
| 428 |
files. |
| 429 |
|
| 430 |
transpose : bool |
| 431 |
Transpose the table before writing. |
| 432 |
|
| 433 |
encoding : str |
| 434 |
Encoding to use to write the data to the file. Note that the default |
| 435 |
encoding is platform dependent, which ensures compatibility with the |
| 436 |
Python open() function. It thus defaults to |
| 437 |
`locale.getpreferredencoding()`. |
| 438 |
|
| 439 |
Raises |
| 440 |
------ |
| 441 |
ValueError: |
| 442 |
When the length of the rows is not constant. |
| 443 |
|
| 444 |
""" |
| 445 |
if not table: |
| 446 |
return |
| 447 |
|
| 448 |
if transpose: |
| 449 |
list_table = list(map(list, zip(*table))) |
| 450 |
else: |
| 451 |
list_table = list(map(list, table)) |
| 452 |
|
| 453 |
if len(set(map(len, list_table))) > 1: |
| 454 |
raise ValueError("Table doesn't have constant row length.") |
| 455 |
|
| 456 |
with open(filename, "w", newline="", encoding=encoding) as fp: |
| 457 |
w = writer(fp, dialect=dialect) |
| 458 |
w.writerows(list_table) |
| 459 |
|
| 460 |
|
| 461 |
def write_dicts( |
| 462 |
items: Iterable[Mapping[_T, Any]], |
| 463 |
filename: "FileDescriptorOrPath", |
| 464 |
dialect: "_DialectLike" = "excel", |
| 465 |
encoding: Optional[str] = None, |
| 466 |
) -> None: |
| 467 |
"""Write a list of dicts to a file |
| 468 |
|
| 469 |
This is a convenience function to write dicts to a file. The header is |
| 470 |
extracted from the keys of the first item, so an OrderedDict is recommended |
| 471 |
to control the order of the headers in the output. If the list of items is |
| 472 |
empty, no output file is created. |
| 473 |
|
| 474 |
Parameters |
| 475 |
---------- |
| 476 |
items : list |
| 477 |
List of dicts to export |
| 478 |
|
| 479 |
filename : str |
| 480 |
The filename of the CSV file to write the table to |
| 481 |
|
| 482 |
dialect : str, SimpleDialect, or csv.Dialect |
| 483 |
The dialect to use. The default is the 'excel' dialect, which |
| 484 |
corresponds to RFC4180. |
| 485 |
|
| 486 |
encoding : str |
| 487 |
Encoding to use to write the data to the file. Note that the default |
| 488 |
encoding is platform dependent, which ensures compatibility with the |
| 489 |
Python open() function. It thus defaults to |
| 490 |
`locale.getpreferredencoding()`. |
| 491 |
|
| 492 |
""" |
| 493 |
if not items: |
| 494 |
return |
| 495 |
|
| 496 |
iterator = iter(items) |
| 497 |
try: |
| 498 |
first = next(iterator) |
| 499 |
except StopIteration: |
| 500 |
return |
| 501 |
|
| 502 |
fieldnames = list(first.keys()) |
| 503 |
with open(filename, "w", newline="", encoding=encoding) as fp: |
| 504 |
w = DictWriter(fp, fieldnames=fieldnames, dialect=dialect) |
| 505 |
w.writeheader() |
| 506 |
w.writerow(first) |
| 507 |
w.writerows(iterator) |