-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.py
54 lines (48 loc) · 1.38 KB
/
config.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
"""
This module contains IO for a config file storing basic parameters
"""
import pathlib
CONFIG_FILE_NAME = "config.txt"
DELIMITER = " = "
def save_parameter(name,value):
d = _open_file()
d[name] = value
_save_file(d)
def load_parameter(name):
d = _open_file()
if name in d:
return d[name]
return None
def _open_file() -> dict:
"""
Opens file and returns dictionary of parameter-value pairs.
:return:
"""
path = pathlib.Path(CONFIG_FILE_NAME)
d = {}
if not path.exists():
return d
with open(path,'r') as f:
for line in f:
if line:
args = line.split(DELIMITER)
key = args[0]
value = args[1]
try:
value = int(value)
except ValueError:
try:
value = float(value)
except ValueError:
if value.lower() == 'true':
value = True
elif value.lower() == 'false':
value = False
d[key] = value
return d
def _save_file(d:dict):
path = pathlib.Path(CONFIG_FILE_NAME)
with open(path, 'w') as f:
for key,value in d.items():
value = str(value).strip().replace('\n','')
f.write(key + DELIMITER + value + '\n')