In: Computer Science
python 3.6:
You will have two functions:
Function 1: update(user_dictionary): This function will take a dictionary entry as user that has keys, ‘username’,’password’,’uid’, and ‘gid’ along with values. You will search if the username is already in your user_list that you get from your userfile.json file that you have created in your previous task.
If the username in your user_dictionary is not in the list that is in your .json file then add the user_dictionary into the existing list and update your userfile.json with the new entry.
If the username in your user_dictionary isin the list that is in your .json file then just update the fields password,uid, and gid based on the information provided.
Function 2: delete(user_name): This function will take a username and remote entry associated with the user.
Previous Task Code:
#!/usr/bin/env python3.6
import pwd
import json
#Task 1
list=pwd.getpwall()
dictionary={}
print(list)
for i in range(len(list)):
with open('list.json','a') as f:
json.dump(list[i].pw_name,f)
json.dump(list[i].pw_passwd,f)
Code to copy:
def update(user_dictionary):
users_List =
json.load(open('userfile.json', 'r'))
indx = next((i for i, item in
enumerate(users_List) if item["username"] ==
user_dictionary.get("username", '')), None)
update = False
if indx:
update =
True
with open('userfile.json', 'w') as
_file:
if update:
users_List[indx] = user_dictionary
else:
users_List.append(user_dictionary)
json.dump(users_List, _file)
def delete(user_name):
users_List =
json.load(open('userfile.json', 'r'))
indx = next((i for i, item in
enumerate(users_List) if item["username"] == username), None)
if indx:
users_List.pop(indx)
with open('userfile.json', 'w') as
_file:
json.dump(users_List, _file)
Code Screenshot: