Debian Codegraph @

petl/io/csv_py3.py

raw
1 # -*- coding: utf-8 -*-
2 import io
3 import csv
4 import logging
5
6
7 from petl.util.base import Table, data
8
9
10 logger = logging.getLogger(__name__)
11 warning = logger.warning
12 info = logger.info
13 debug = logger.debug
14
15
16 def fromcsv_impl(source, **kwargs):
17 return CSVView(source, **kwargs)
18
19
20 class CSVView(Table):
21
22 def __init__(self, source, encoding, errors, header, **csvargs):
23 self.source = source
24 self.encoding = encoding
25 self.errors = errors
26 self.csvargs = csvargs
27 self.header = header
28
29 def __iter__(self):
30 if self.header is not None:
31 yield tuple(self.header)
32 with self.source.open('rb') as buf:
33 csvfile = io.TextIOWrapper(buf, encoding=self.encoding,
34 errors=self.errors, newline='')
35 try:
36 reader = csv.reader(csvfile, **self.csvargs)
37 for row in reader:
38 yield tuple(row)
39 finally:
40 csvfile.detach()
41
42
43 def tocsv_impl(table, source, **kwargs):
44 _writecsv(table, source=source, mode='wb', **kwargs)
45
46
47 def appendcsv_impl(table, source, **kwargs):
48 _writecsv(table, source=source, mode='ab', **kwargs)
49
50
51 def _writecsv(table, source, mode, write_header, encoding, errors, **csvargs):
52 rows = table if write_header else data(table)
53 with source.open(mode) as buf:
54 # wrap buffer for text IO
55 csvfile = io.TextIOWrapper(buf, encoding=encoding, errors=errors,
56 newline='')
57 try:
58 writer = csv.writer(csvfile, **csvargs)
59 for row in rows:
60 writer.writerow(row)
61 csvfile.flush()
62 finally:
63 csvfile.detach()
64
65
66 def teecsv_impl(table, source, **kwargs):
67 return TeeCSVView(table, source=source, **kwargs)
68
69
70 class TeeCSVView(Table):
71
72 def __init__(self, table, source=None, encoding=None,
73 errors='strict', write_header=True, **csvargs):
74 self.table = table
75 self.source = source
76 self.write_header = write_header
77 self.encoding = encoding
78 self.errors = errors
79 self.csvargs = csvargs
80
81 def __iter__(self):
82 with self.source.open('wb') as buf:
83 # wrap buffer for text IO
84 csvfile = io.TextIOWrapper(buf, encoding=self.encoding,
85 errors=self.errors, newline='')
86 try:
87 writer = csv.writer(csvfile, **self.csvargs)
88 it = iter(self.table)
89 try:
90 hdr = next(it)
91 except StopIteration:
92 return
93 if self.write_header:
94 writer.writerow(hdr)
95 yield tuple(hdr)
96 for row in it:
97 writer.writerow(row)
98 yield tuple(row)
99 csvfile.flush()
100 finally:
101 csvfile.detach()