File: _utils.py

package info (click to toggle)
python-clevercsv 0.8.3%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,076 kB
  • sloc: python: 6,184; ansic: 870; makefile: 90
file content (58 lines) | stat: -rw-r--r-- 1,563 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# -*- coding: utf-8 -*-

from typing import Any
from typing import List
from typing import Optional

from clevercsv import __version__
from clevercsv.dialect import SimpleDialect


def parse_int(val: Any, name: str) -> Optional[int]:
    """Parse a number to an integer if possible"""
    if val is None:
        return val
    try:
        return int(val)
    except ValueError:
        raise ValueError(
            f"Please provide a number for {name}, instead of {val}"
        )


def generate_code(
    filename: str,
    dialect: SimpleDialect,
    encoding: Optional[str],
    use_pandas: bool = False,
) -> List[str]:
    assert dialect.quotechar is not None
    d = '"\\t"' if dialect.delimiter == "\t" else f'"{dialect.delimiter}"'
    q = '"%s"' % (dialect.quotechar.replace('"', '\\"'))
    e = repr(f"{dialect.escapechar}").replace("'", '"')
    base = [
        "",
        f"# Code generated with CleverCSV version {__version__}",
        "",
        "import clevercsv",
    ]
    if use_pandas:
        return [
            *base,
            "",
            f'df = clevercsv.read_dataframe("{filename}", delimiter={d}, '
            f"quotechar={q}, escapechar={e})",
            "",
        ]

    enc = "None" if encoding is None else f'"{encoding}"'
    lines = [
        *base,
        "",
        f'with open("{filename}", "r", newline="", encoding={enc}) as fp:',
        "    reader = clevercsv.reader(fp, "
        + f"delimiter={d}, quotechar={q}, escapechar={e})",
        "    rows = list(reader)",
        "",
    ]
    return lines