File: to_csv.py

package info (click to toggle)
python-agate 1.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,996 kB
  • sloc: python: 8,512; makefile: 126
file content (45 lines) | stat: -rw-r--r-- 1,141 bytes parent folder | download | duplicates (2)
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
import os


def to_csv(self, path, **kwargs):
    """
    Write this table to a CSV. This method uses agate's builtin CSV writer,
    which supports unicode on both Python 2 and Python 3.

    ``kwargs`` will be passed through to the CSV writer.

    The ``lineterminator`` defaults to the newline character (LF, ``\\n``).

    :param path:
        Filepath or file-like object to write to.
    """
    from agate import csv

    if 'lineterminator' not in kwargs:
        kwargs['lineterminator'] = '\n'

    close = True
    f = None

    try:
        if hasattr(path, 'write'):
            f = path
            close = False
        else:
            dirpath = os.path.dirname(path)

            if dirpath and not os.path.exists(dirpath):
                os.makedirs(dirpath)

            f = open(path, 'w')

        writer = csv.writer(f, **kwargs)
        writer.writerow(self._column_names)

        csv_funcs = [c.csvify for c in self._column_types]

        for row in self._rows:
            writer.writerow(tuple(csv_funcs[i](d) for i, d in enumerate(row)))
    finally:
        if close and f is not None:
            f.close()