OLD | NEW |
---|---|
(Empty) | |
1 #!/usr/bin/python | |
2 # Copyright 2016 The Chromium Authors. All rights reserved. | |
3 # Use of this source code is governed by a BSD-style license that can be | |
4 # found in the LICENSE file. | |
5 """Converts csv files to machine usable json | |
qyearsley
2016/07/18 21:02:25
One blank line can be added above the docstring.
| |
6 | |
7 TODO(raikiri): DO NOT SUBMIT without a detailed description of csv_to_json. | |
qyearsley
2016/07/18 21:02:25
This message can be removed.
| |
8 """ | |
9 | |
10 import sys | |
11 import csv | |
12 import json | |
13 import argparse | |
qyearsley
2016/07/18 21:02:25
Imports should be sorted.
| |
14 | |
15 def main(argv): | |
qyearsley
2016/07/18 21:02:25
Formatting note: usually there's two blank lines b
| |
16 parser = argparse.ArgumentParser() | |
17 parser.add_argument('filename', metavar='filename', | |
18 help='the path to the csv') | |
qyearsley
2016/07/18 21:02:25
the path to the input CSV file
| |
19 parser.add_argument('-o', '--output', | |
20 help='the output file name') | |
qyearsley
2016/07/18 21:02:25
The help lines might look good if capitalized and
| |
21 args = parser.parse_args(argv) | |
qyearsley
2016/07/18 21:02:25
The argparse library can also access sys.argv by i
| |
22 convert_csv_to_json(args.filename) | |
23 | |
24 | |
25 def convert_csv_to_json(filename, output_filename=None): | |
26 out = output_filename or (filename + '.json') | |
27 dict_list = [] | |
28 jsonfile = open(out, 'w') | |
qyearsley
2016/07/18 21:02:25
jsonfile -> json_file
| |
29 with open(filename) as csvfile: | |
qyearsley
2016/07/18 21:02:25
csvfile -> csv_file
| |
30 readerobj = csv.DictReader(csvfile) | |
qyearsley
2016/07/18 21:02:25
readerobj -> reader
| |
31 for row in readerobj: | |
32 dict_list.append(row) | |
33 json.dump(dict_list, jsonfile, indent=4) | |
34 | |
qyearsley
2016/07/18 21:02:25
We can have two blank lines between the last funct
| |
35 if __name__ == '__main__': | |
36 main(sys.argv[1:]) | |
OLD | NEW |