File: csv.py

package info (click to toggle)
python-petl 1.7.17-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,224 kB
  • sloc: python: 22,617; makefile: 109; xml: 9
file content (199 lines) | stat: -rw-r--r-- 6,059 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division


# standard library dependencies
from petl.compat import PY2


# internal dependencies
from petl.util.base import Table
from petl.io.sources import read_source_from_arg, write_source_from_arg
if PY2:
    from petl.io.csv_py2 import fromcsv_impl, tocsv_impl, appendcsv_impl, \
        teecsv_impl
else:
    from petl.io.csv_py3 import fromcsv_impl, tocsv_impl, appendcsv_impl, \
        teecsv_impl


def fromcsv(source=None, encoding=None, errors='strict', header=None, 
            **csvargs):
    """
    Extract a table from a delimited file. E.g.::

        >>> import petl as etl
        >>> import csv
        >>> # set up a CSV file to demonstrate with
        ... table1 = [['foo', 'bar'],
        ...           ['a', 1],
        ...           ['b', 2],
        ...           ['c', 2]]
        >>> with open('example.csv', 'w') as f:
        ...     writer = csv.writer(f)
        ...     writer.writerows(table1)
        ...
        >>> # now demonstrate the use of fromcsv()
        ... table2 = etl.fromcsv('example.csv')
        >>> table2
        +-----+-----+
        | foo | bar |
        +=====+=====+
        | 'a' | '1' |
        +-----+-----+
        | 'b' | '2' |
        +-----+-----+
        | 'c' | '2' |
        +-----+-----+

    The `source` argument is the path of the delimited file, all other keyword
    arguments are passed to :func:`csv.reader`. So, e.g., to override the
    delimiter from the default CSV dialect, provide the `delimiter` keyword
    argument.

    Note that all data values are strings, and any intended numeric values will
    need to be converted, see also :func:`petl.transform.conversions.convert`.

    """

    source = read_source_from_arg(source)
    csvargs.setdefault('dialect', 'excel')
    return fromcsv_impl(source=source, encoding=encoding, errors=errors, 
                        header=header, **csvargs)


def fromtsv(source=None, encoding=None, errors='strict', header=None, 
            **csvargs):
    """
    Convenience function, as :func:`petl.io.csv.fromcsv` but with different
    default dialect (tab delimited).

    """

    csvargs.setdefault('dialect', 'excel-tab')
    return fromcsv(source, encoding=encoding, errors=errors, header=header, **csvargs)


def tocsv(table, source=None, encoding=None, errors='strict', write_header=True,
          **csvargs):
    """
    Write the table to a CSV file. E.g.::

        >>> import petl as etl
        >>> table1 = [['foo', 'bar'],
        ...           ['a', 1],
        ...           ['b', 2],
        ...           ['c', 2]]
        >>> etl.tocsv(table1, 'example.csv')
        >>> # look what it did
        ... print(open('example.csv').read())
        foo,bar
        a,1
        b,2
        c,2

    The `source` argument is the path of the delimited file, and the optional
    `write_header` argument specifies whether to include the field names in the
    delimited file.  All other keyword arguments are passed to
    :func:`csv.writer`. So, e.g., to override the delimiter from the default
    CSV dialect, provide the `delimiter` keyword argument.

    Note that if a file already exists at the given location, it will be
    overwritten.

    """

    source = write_source_from_arg(source)
    csvargs.setdefault('dialect', 'excel')
    tocsv_impl(table, source=source, encoding=encoding, errors=errors,
               write_header=write_header, **csvargs)


Table.tocsv = tocsv


def appendcsv(table, source=None, encoding=None, errors='strict',
              write_header=False, **csvargs):
    """
    Append data rows to an existing CSV file. As :func:`petl.io.csv.tocsv`
    but the file is opened in append mode and the table header is not written by
    default.

    Note that no attempt is made to check that the fields or row lengths are
    consistent with the existing data, the data rows from the table are simply
    appended to the file.

    """

    source = write_source_from_arg(source, mode='ab')
    csvargs.setdefault('dialect', 'excel')
    appendcsv_impl(table, source=source, encoding=encoding, errors=errors,
                   write_header=write_header, **csvargs)


Table.appendcsv = appendcsv


def totsv(table, source=None, encoding=None, errors='strict',
          write_header=True, **csvargs):
    """
    Convenience function, as :func:`petl.io.csv.tocsv` but with different
    default dialect (tab delimited).

    """

    csvargs.setdefault('dialect', 'excel-tab')
    return tocsv(table, source=source, encoding=encoding, errors=errors,
                 write_header=write_header, **csvargs)


Table.totsv = totsv


def appendtsv(table, source=None, encoding=None, errors='strict',
              write_header=False, **csvargs):
    """
    Convenience function, as :func:`petl.io.csv.appendcsv` but with different
    default dialect (tab delimited).

    """

    csvargs.setdefault('dialect', 'excel-tab')
    return appendcsv(table, source=source, encoding=encoding, errors=errors,
                     write_header=write_header, **csvargs)


Table.appendtsv = appendtsv


def teecsv(table, source=None, encoding=None, errors='strict', write_header=True,
           **csvargs):
    """
    Returns a table that writes rows to a CSV file as they are iterated over.

    """

    source = write_source_from_arg(source)
    csvargs.setdefault('dialect', 'excel')
    return teecsv_impl(table, source=source, encoding=encoding,
                       errors=errors, write_header=write_header,
                       **csvargs)


Table.teecsv = teecsv


def teetsv(table, source=None, encoding=None, errors='strict', write_header=True,
           **csvargs):
    """
    Convenience function, as :func:`petl.io.csv.teecsv` but with different
    default dialect (tab delimited).

    """

    csvargs.setdefault('dialect', 'excel-tab')
    return teecsv(table, source=source, encoding=encoding, errors=errors,
                  write_header=write_header, **csvargs)


Table.teetsv = teetsv