forked from wireservice/csvkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
in2csv
executable file
·66 lines (50 loc) · 2.55 KB
/
in2csv
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
#!/usr/bin/env python
import sys
from csvkit import convert
from csvkit.cli import CSVFileType, CSVKitUtility
class In2CSV(CSVKitUtility):
description = 'Convert common, but less awesome, tabular data formats to CSV.'
epilog='Some command line flags only pertain to specific input formats.'
override_flags = 'f'
def add_arguments(self):
self.argparser.add_argument('file', metavar="FILE", nargs='?', default=sys.stdin,
help='The CSV file to operate on. If omitted, will accept input on STDIN.')
self.argparser.add_argument('-f', '--format', dest='format',
help='The format of the input file. If not specified will be inferred from the file type. Supported formats: %s.' % ', '.join(sorted(convert.SUPPORTED_FORMATS)))
self.argparser.add_argument('-s', '--schema', dest='schema', type=CSVFileType(),
help='Specifies a CSV-formatted schema file for converting fixed-width files. See documentation for details.')
self.argparser.add_argument('-k', '--key', dest='key',
help='Specifies a top-level key to use look within for a list of objects to be converted when processing JSON.')
def main(self):
if self.args.file == '<stdin>' and not self.args.format:
sys.exit('You must specify a format when providing data via STDIN (pipe).')
if self.args.format:
format = self.args.format
if format not in convert.SUPPORTED_FORMATS:
sys.exit('"%s" is not a supported format' % self.args.format)
elif self.args.schema:
format = 'fixed'
elif self.args.key:
format = 'js'
else:
format = convert.guess_format(self.args.file)
if not format:
sys.exit('Unable to automatically determine the format of the input file. Try specifying a format with --format.')
if isinstance(self.args.file, file):
f = self.args.file
elif format == 'xls':
f = open(self.args.file, 'rb')
else:
f = open(self.args.file, 'rU')
kwargs = self.reader_kwargs
if self.args.schema:
kwargs['schema'] = self.args.schema
if self.args.key:
kwargs['key'] = self.args.key
# Fixed width can be processed as a stream
if format == 'fixed':
kwargs['output'] = sys.stdout
sys.stdout.write(convert.convert(f, format, **kwargs))
if __name__ == "__main__":
utility = In2CSV()
utility.main()