Demand:
1, the user's registration information is written in the JSON file
2, the Read and write files to extract the repeated operation as a function, concise code
Realize:
ImportJSONdefOp_data (filename,dic=None):ifDic:#If there is content, write the filewith open (filename,'W', encoding='Utf-8') as Fw:json.dump (Dic,fw,ensure_ascii=false,indent=4) Else:#no content, just read the file.With open (filename,encoding='Utf-8') as fr:returnJson.load (FR)#Convert a JSON file to a dictionaryFILENAME ='User_info.json'All_user=Op_data (FILENAME) forIinchRange (3): Choice= Input ('Input Selection: 1, registration, 2, delete') ifChoice = ='1':#RegisterUsername = input ('Enter a registered user name'). Strip () passwd= Input ('Enter your registration password'). Strip ()ifUsernameinchAll_user:Print('user already exists') Else: All_user[username]=passwd op_data (filename,all_user)elifChoice = ='2':#DeleteUsername = input ('Enter Delete user name'). Strip () All_user.pop (username) op_data (FILENAME, All_user)
Python JSON Practice _ Read and write file functions