This my below code. It works if the file paths and name1/2/3 under hotel_config are defined and written inside the json_updater. But if I don't put name2 and location_medailia, the code will just throw an error and won't update any paths. Is there a way I can bypass this error or tell it to ignore it? And just update the locations if they are given inside the json_updater.
def password_updater_HotelsTAG(self,hotel_ID,pwd):
with open('Json_updater.json','r',encoding="utf-8-sig") as f:
json_updater_info = commentjson.load(f) #takes the information from Json_updater.json
password = pwd
for i in json_updater_info["Hotel_Config"]:
if i["Hotel_ID"] == str(hotel_ID):
file_name = i["name"]
file_name2 =i["name2"]
file_name3 =i["name3"]
try:
with open(f"{i['location_Daily']}\\{file_name}",'r') as f:
print("Updating file: " , file_name)
json_info = commentjson.load(f) #Gets info from the json file
json_info['hotels'][0]['password'] = password
print("location_Daily exists")
with open(f"{i['location_Daily']}\\{file_name}",'w') as f:
commentjson.dump(json_info,f,indent = 4) #updates the password
print("location_Daily password updated")
except FileNotFoundError:
print("location_Daily file not found...Please check the path again")
try:
with open(f"{i['location_Medallia']}\\{file_name2}",'r') as f:
print("Updating file: " , file_name2)
json_info = commentjson.load(f) #Gets info from the json file
json_info['password'] = password
print("location_Medallia exists")
with open(f"{i['location_Medallia']}\\{file_name2}",'w') as f:
commentjson.dump(json_info,f,indent = 4) #updates the password
print("location_Medallia password updated")
except FileNotFoundError:
print("location_Medallia file not found...Please check the path again")
try:
with open(f"{i['Third_location']}\\{file_name3}",'r') as f:
print("Updating file: " , file_name3)
json_info = commentjson.load(f) #Gets info from the json file
json_info['password'] = password
print("Third Location exists")
with open(f"{i['location_Medallia']}\\{file_name3}",'w') as f:
commentjson.dump(json_info,f,indent = 4) #updates the password
print("location_Medallia password updated")
except FileNotFoundError:
print("Third Location not found file not found...Please check the path again")
Json_updater.json:
{
"Hotel_Config": [
{
"name": "test.json",
"location_Daily": "C:\\Users\\Test\\Desktop\\Projects\\BOT\\Configs\\",
"name2": "test.json",
"location_Medallia": "C:\\Users\\Test\\Desktop\\Projects\\BOT2\\Configs\\",
"name3": "test",
"Third_location": "C:\\Users\\Test\\Desktop\\Projects\\BOT3\\Configs\\",
"Hotel_ID": "1"
#this works, no errors
},
{
"name": "test.json",
"location_Daily": "C:\\Users\\Test\\Desktop\\Projects\\BOT\\Configs\\",
"name2": "test.json",
"location_Medallia": "C:\\Users\\Test\\Desktop\\Projects\\BOT2\\Configs\\",
"Hotel_ID": "1"
#this does not work. Throws error
},