forked from WFP-VAM/DataLibraryAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
40 lines (34 loc) · 1.28 KB
/
utils.py
File metadata and controls
40 lines (34 loc) · 1.28 KB
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
from datetime import date
import csv
def normalize_json(data: dict) -> dict:
"""Flatten json"""
new_data = dict()
for key, value in data.items():
if not isinstance(value, dict):
new_data[key] = value
else:
for k, v in value.items():
new_data[key + "_" + k] = v
return new_data
def create_csv(data, filename = "output"):
"""Create CSV file based on data"""
# Get today's date in format YYY_MM_DD
today = str(date.today()).replace("-", "_")
# Create file name with today's date and data
filename = f"{today}_{filename}.csv"
if type(data[0]) == str:
with open(filename, 'w', newline="") as csvfile:
writer = csv.writer(csvfile)
for survey in data:
writer.writerow([survey])
else:
try:
with open(filename, 'w', newline="", encoding="utf-8") as csvfile:
# get row header
header = list(data[0].keys())
writer = csv.DictWriter(csvfile, fieldnames = header, extrasaction='ignore')
writer.writeheader()
writer.writerows(data)
except FileNotFoundError:
print(f"Unable to locate {filename}")
print(f"{filename} saved in current directory")