-
Notifications
You must be signed in to change notification settings - Fork 2
/
writers.py
79 lines (65 loc) · 2.47 KB
/
writers.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
77
78
79
"""Functions for saving objects to file after they have been JSON serialized."""
import json
import pathlib
from typing import Dict, List, Optional
from authorityspoke.io import filepaths
def case_to_file(
case: Dict,
filename: Optional[str] = None,
directory: Optional[pathlib.Path] = None,
filepath: Optional[pathlib.Path] = None,
) -> None:
r"""
Save one case from an API response as a JSON file.
:param results:
A dict representing a case, in the format
of the Caselaw Access Project API.
:param filename:
Filename (not including the directory) for the
file where the downloaded opinion should be saved.
:param directory:
A :py:class:`~pathlib.Path` object specifying the directory where the
downloaded opinion should be saved. If ``None`` is given, the current
default is ``example_data/cases``\.
:param filepath:
Complete path to the location where the JSON file should be saved,
including filename.
"""
validated_filepath = filepaths.make_filepath(
filename, directory, filepath, default_folder="cases"
)
with open(validated_filepath, "w") as fp:
json.dump(case, fp, ensure_ascii=False, indent=4)
def cases_to_file(
results: List[Dict],
filename: Optional[str] = None,
directory: Optional[pathlib.Path] = None,
filepath: Optional[pathlib.Path] = None,
) -> None:
"""
Save cases from an API response as JSON files.
:param results:
A list of dicts representing cases, in the format
of the Caselaw Access Project API.
:param filename:
Filename (not including the directory) for the
file where the downloaded opinion should be saved.
:param directory:
A :py:class:`~pathlib.Path` object specifying the directory where the
downloaded opinion should be saved. If ``None`` is given, the current
default is ``example_data/cases``.
:param filepath:
Complete path to the location where the JSON file should be saved,
including filename.
"""
for number, case in enumerate(results):
if not filename:
mangled_filename = f'{case["id"]}.json'
else:
mangled_filename = filename
if number > 0:
mangled_filename = mangled_filename.replace(".", f"_{number}.")
case_to_file(
case=case, filename=mangled_filename, directory=directory, filepath=filepath
)
return None