Update: thanks to the comments I changed the code the following way (it's not finished yet).
cmd_parameter_user = "config1.cfg"
cmd_parameter_global = "global.cfg"
config_file_user = []
config_file_global = []
conf_key_split1 = '.'
conf_key_split2 = '='
conf_key_split3 = ','
dict_config_user = {}
dict_config_global = {}
dict_config = {}
if len(sys.argv) == 2:
cmd_parameter_user = sys.argv[1]
else:
print("Error: there should be only one argument after program name - config file name")
exit(-1)
def read_file(filename, message):
# function for reading from file to list of lines
try:
with open(filename) as file_:
return file_.readlines()
except FileNotFoundError:
print(message.format(filename))
exit(-1)
# reading user's and global config files
config_file_user = read_file(cmd_parameter_user, "File '{}' not exists or not available")
config_file_global = read_file(cmd_parameter_global, "File '{}' not exists or not available")
def parse_list(filename, dictname):
# function for parsing list of lines into a dict
for line in filename:
if line.startswith(conf_key_split1):
line = line.rstrip().split(conf_key_split1)
line = line[1]
(key, val) = line.split(conf_key_split2)
dictname.update({key: val})
# parsing user's and global config files
parse_list(config_file_user, dict_config_user)
parse_list(config_file_global, dict_config_global)
def update_dicts(dictname1, dictname2):
# function for updating (merging) dicts
dictname1.update(dictname2)
return dictname1
def value_from_dict(param):
# function for searching the value of param in dict
if param in dict_config:
return dict_config.get(param)
else:
print('The value of the parameter "', param, '" was not found in either', cmd_parameter_global, 'or', cmd_parameter_user)
exit(-1)
dict_config = update_dicts(dict_config_global, dict_config_user)
Usage:
names = int(value_from_dict('names'))