-
Notifications
You must be signed in to change notification settings - Fork 1
/
helper.py
41 lines (29 loc) · 1.06 KB
/
helper.py
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
"""A helper module containing methods for exporting data.
Provides the necessary tools to export an object to either a csv or json file.
"""
import csv
import json
def export_to_csv(obj, file_name, first=False):
"""Export a list of dictionaries to a csv file.
Args:
=====
obj (list): A list of dictionaries representing the object to be exported
file_name (str): The destination file name
first (boolean): Whether this is the first batch to be exported
"""
header = obj[0].keys()
write_type = 'w' if first else 'a'
with open(file_name, write_type) as output_file:
dict_writer = csv.DictWriter(output_file, header)
if first:
dict_writer.writeheader()
dict_writer.writerows(obj)
def export_to_json(obj, file_name):
"""Export a list of dictionaries to a json file.
Args:
=====
obj (list): A list of dictionaries representing the object to be exported
file_name (str): The destination file name
"""
with open(file_name, 'w') as output_file:
json.dump(obj, output_file)