Answer the question
In order to leave comments, you need to log in
How efficient is my code if I read it in its entirety each time to change the key-value of the store?
I created a console script to work with key-value storage. In order to read some value from it by key or add a new value, I read it completely every time. Is this normal practice or should I do something else?
The storage works like this: passing --key --value creates a value for the key (or adds it if the key already exists). Passing --key prints the key values.
import os
import tempfile
import argparse
import json
import os
import tempfile
parser = argparse.ArgumentParser()
parser.add_argument('--key')
parser.add_argument('--value')
parser_args = parser.parse_args()
storage_path = os.path.join(tempfile.gettempdir(), 'storage.data')
try:
with open(storage_path, 'r') as f:
data = json.load(f)
except json.decoder.JSONDecodeError:
data = {}
with open(storage_path, 'w') as f:
json.dump(data, f)
except FileNotFoundError:
data = {}
with open(storage_path, 'w') as f:
json.dump(data, f)
if parser_args.value is None:
with open(storage_path, 'r') as f:
data = json.load(f)
try:
print(*data[parser_args.key], sep=', ')
except KeyError:
print(None)
if (parser_args.key is not None) and (parser_args.value is not None):
with open(storage_path, 'r') as f:
data_local = json.load(f)
with open(storage_path, 'w') as f:
try:
data_local[parser_args.key].append(parser_args.value)
except KeyError:
data_local[parser_args.key] = [parser_args.value]
json.dump(data_local, f, indent=4)
Answer the question
In order to leave comments, you need to log in
In order to read some value from it by key or add a new value, I read it completely every time. Is this normal practice or should I do something else?
PS what is the best way to write: if smth is None or is it better to write if smth?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question