-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey_value_pair_storage_v2.py
55 lines (39 loc) · 1.27 KB
/
key_value_pair_storage_v2.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
import argparse
import json
import os
import tempfile
def read_data(storage_path):
if not os.path.exists(storage_path):
return {}
with open(storage_path, 'r') as file:
raw_data = file.read()
if raw_data:
return json.loads(raw_data)
return {}
def write_data(storage_path, data):
with open(storage_path, 'w') as f:
f.write(json.dumps(data))
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('--key', help='Key')
parser.add_argument('--val', help='Value')
return parser.parse_args()
def put(storage_path, key, value):
data = read_data(storage_path)
data[key] = data.get(key, list())
data[key].append(value)
write_data(storage_path, data)
def get(storage_path, key):
data = read_data(storage_path)
return data.get(key, [])
def main(storage_path):
args = parse()
if args.key and args.val:
put(storage_path, args.key, args.val)
elif args.key:
print(*get(storage_path, args.key), sep=', ')
else:
print('The program is called with invalid parameters.')
if __name__ == '__main__':
storage_path = os.path.join(tempfile.gettempdir(), 'storage.data')
main(storage_path)