-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.py
68 lines (53 loc) · 1.67 KB
/
core.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
import json
import os
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
def __get_file_type(fpath: str) -> str:
if fpath.endswith(".jsonl"):
return "jsonl"
elif fpath.endswith(".json"):
return "json"
else:
return "text"
def load(fpath: str | Path) -> Union[List[str], Dict]:
fpath = str(fpath)
ftype = __get_file_type(fpath)
if ftype == "jsonl":
with open(fpath, "r") as f:
data = [json.loads(line) for line in f.readlines()]
elif ftype == "json":
with open(fpath, "r") as f:
data = json.load(f)
else:
with open(fpath, "r") as f:
data = [line.strip() for line in f.readlines()]
return data
def save(
data: Union[List[Any], Dict], fpath: str | Path, indent: Optional[int] = None
) -> None:
fpath = str(fpath)
ftype = __get_file_type(fpath)
if ftype == "jsonl":
with open(fpath, "w") as f:
f.write("\n".join([json.dumps(d) for d in data]))
elif ftype == "json":
with open(fpath, "w") as f:
json.dump(data, f, indent=indent)
else:
with open(fpath, "w") as f:
f.write("\n".join(data))
def add(data: Dict, fpath: str | Path):
fpath = str(fpath)
assert isinstance(
data, dict
), "Currently, only adding dict data to jsonl file is supported."
assert fpath.endswith(
".jsonl"
), "Currently, only adding dict data to jsonl file is supported."
exists = os.path.exists(fpath)
with open(fpath, "a") as f:
if exists:
f.write("\n")
else:
print(f"Creating {fpath}")
f.write(json.dumps(data))