-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.py
76 lines (62 loc) · 1.99 KB
/
common.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
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
import csv
import sys
maxInt = sys.maxsize
while True:
# decrease the maxInt value by factor 10
# as long as the OverflowError occurs.
try:
csv.field_size_limit(maxInt)
break
except OverflowError:
maxInt = int(maxInt / 10)
def load_csv_as_dict(csv_path, fieldnames=None, delimiter=None):
""" Loads the csv DictReader
Parameters
----------
csv_path : str
Path to csv
fieldnames : list of str
List of fieldnames, if None then fieldnames are take from the first row
delimiter : str
Delimiter to split on, default \t
Returns
-------
csv.DictReader
DictReader object of path
"""
delimiter = delimiter or "\t"
f = open(csv_path, encoding='utf8')
c = csv.DictReader(f, fieldnames=fieldnames, delimiter=delimiter)
return c
def write_rows_to_csv(rows_to_write, csv_path, fieldnames=None, mode=None, delimiter=None, write_header=None):
""" Write the rows the csv at the path
Parameters
----------
rows_to_write : list of dict
Rows to write to the CSV
csv_path : str
Path to csv
fieldnames : list of str
List of fieldnames for csv. Default of keys of first row in rows_to_write
mode : str
Mode to write to file (w for write, a for append)
delimiter : str
Delimiter to join rows on, default \t
write_header : bool
Whether to write header before writing rows, default false
Returns
-------
csv.DictWriter
DictWriter object of path
"""
if rows_to_write:
mode = mode or "w"
write_header = write_header if write_header is not None else False
delimiter = delimiter or '\t'
fieldnames = fieldnames or list(rows_to_write[0].keys())
f = open(csv_path, mode, encoding='utf8', newline='')
c = csv.DictWriter(f, fieldnames=fieldnames, delimiter=delimiter)
if write_header:
c.writeheader()
c.writerows(rows_to_write)
f.close()