-
Notifications
You must be signed in to change notification settings - Fork 2
/
io_util.py
63 lines (41 loc) · 1.55 KB
/
io_util.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
import logging
import pyhocon
from os.path import join
import os
import ujson as json
import pickle
logger = logging.getLogger(__name__)
def parse_configs(config_path='experiments.conf'):
return pyhocon.ConfigFactory.parse_file(config_path)
def get_config(config_name, create_dir=True, config_path='experiments.conf'):
logger.info("Experiment: {}".format(config_name))
config = parse_configs(config_path)[config_name]
config['log_dir'] = join(config['log_root'], config_name)
config['tb_dir'] = join(config['log_root'], 'tensorboard')
if create_dir:
os.makedirs(config['log_dir'], exist_ok=True)
os.makedirs(config['tb_dir'], exist_ok=True)
# logger.info(pyhocon.HOCONConverter.convert(config, 'hocon'))
return config
def read_jsonlines(file_path):
with open(file_path, 'r') as f:
return [json.loads(line) for line in f if line.strip()]
def write_jsonlines(file_path, instances):
with open(file_path, 'w') as f:
for inst in instances:
f.write(f'{json.dumps(inst)}\n')
def read_json(file_path):
with open(file_path, 'r') as f:
return json.load(f)
def write_json(file_path, data):
with open(file_path, 'w') as f:
json.dump(data, f)
def read_pickle(file_path):
with open(file_path, 'rb') as f:
return pickle.load(f)
def write_pickle(file_path, data):
with open(file_path, 'wb') as f:
pickle.dump(data, f, protocol=4)
def read_plain(file_path):
with open(file_path, 'r') as f:
return [line.strip() for line in f if line.strip()]