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)
import json
def update(user_data):
user_list = json.load(open('/home/i0504/Documents/test_json.json', 'r'))
index = next((i for i, item in enumerate(user_list) if item["username"] == user_data.get("username", '')), None)
update = False
if index:
update = True
with open('/home/i0504/Documents/test_json.json', 'w') as _file:
if update:
user_list[index] = user_data
else:
user_list.append(user_data)
json.dump(user_list, _file)
def delete(user_name):
user_list = json.load(open('/home/i0504/Documents/test_json.json', 'r'))
index = next((i for i, item in enumerate(user_list) if item["username"] == username), None)
if index:
user_list.pop(index)
with open('/home/i0504/Documents/test_json.json', 'w') as _file:
json.dump(user_list, _file)
Get Answers For Free
Most questions answered within 1 hours.