Management System in Python - #3 - Removing Records/Users

Submitted by: 
Language: 
Visitors have accessed this post 247 times.

Introduction:
In this tutorial we will continue making our local user management system in Python. In part two we made the list users and change file path options, now we are going to be making a remove users function/choice/option in the menu.

Important:
Although I keep interchanging the words records and users, this system can be used to keep any records of information, but I am using this example as a user management system.

Instructions Update:
Although this does not affect the program in any way, you may want to update your instructions with the new options...

  1. print("Welcome to my local file user management system [Created by Yorkiebar]. There are two options; 0=exit, 1=add user, 2=list users, 3=remove user, 10=change file path...\n")

Options:
Now we want to add a new option to the main menu system, we'll use option 3 since we used it in the instructions text...

  1. elif (user is 3):
  2. removeUser();

The removeUser Function:
So now we need to create the removeUser function, this function will require an additional function called checkRecord to check if the specified record exists. First we take a couple of pieces of information from the user to select which record to remove...

  1. def removeUser():
  2. user = input("To remove a user, please enter id={id} - this is the record number, use option 2 to list the records and get the record number, or enter a piece of information to see a list of matched records...");
  3. if (user.lower().startswith("id=")):
  4. recordID = int(user[3:])
  5. print("Checking to see if a record with the id of " + str(recordID) + " exists...");
  6. recordExists = checkRecord(recordID);
  7. if (recordExists):
  8. print("Record exists. Deleting... ");
  9. deleteRecord(recordID);
  10. else:
  11. print("That record ID does not exist. Please try again.");
  12. else:
  13. #Information entered, not a record ID.
  14. records = getMatchedRecords(user.lower())
  15. if (len(records) > 0):
  16. print('Found the following ' + str(len(records)) + ' results...')
  17. else:
  18. print('Found no results matching the inforamtion:\n' + user)
  19. id = 0
  20. for record in records:
  21. print(str(id) + " " + record)
  22. id += 1
  23. going = 1
  24. while (going):
  25. try:
  26. choice = int(input('Enter the record id to delete, or -1 to cancel... '))
  27. except ValueError:
  28. print('That entry is not valid. Enter a record id or -1 to cancel.')
  29. if (choice == -1):
  30. going = 0
  31. break
  32. else:
  33. if (choice > -1 and choice < len(records)):
  34. deleteRecordInformation(records[choice])
  35. going = 0
  36. else:
  37. print('That choice is not valid. Please try again.')

As you can see, this is a massive function in relative to the others we currently have, although there is not too much going on. First we create another menu system for the user to decide whether they want to enter a record ID or information to determine which record to delete.

If they enter "id=" followed by a valid ID, we call the deleteRecord function and pass the record ID entered by the user. We use a checkRecord function to check if the ID is valid or not.

If they did not start the entry with "id=", they must of entere information. So we call a function named getMatchedRecords and pass it the users entered string in lower case (easier to compare), assign it to a records variable, print out the amount of results and each one individually each with it's own ID.

We then create another menu system for the user to enter the ID of the record to delete. If they enter -1 we exit (cancel) the loop without performing any changes. If the choice is valid we call a function named deleteRecordInformation and pass it the actual line in the management file indexed at the option entered by the user. We then break out of the loop by changing the while loops conditions to false (the going variable).

getMatchedRecords Function:
This function is used to return a list of strings (records within the management file). We simply open a file stream with the access mode as read ('r'), read all the lines and return them...

  1. def getMatchedRecords(info):
  2. records = []
  3. file = open(fileName, 'r')
  4. for line in file.readlines():
  5. if (info in line.lower()):
  6. records.append(line)
  7. return records

checkRecord Function:
This function is used to check if a full record line exists within the file. We open the stream, read and compare each line of the file. If it finds the same line as parsed to the function, we return 1 (true), otherwise we return 0 (false)...

  1. def checkRecord(id):
  2. file = open(fileName, 'r')
  3. lines = file.readlines()
  4. print(len(lines))
  5. if (len(lines) >= id):
  6. return 1;
  7. return 0;

deleteRecordInformation Function:
This function is self explanatory. We iterate through each line of the file stream, compare the line as a string to the parsed string, if they're not the same we add the iterating line to a new list named 'newLines'. Then we close the read file stream, open a new write file stream, write each string in the newLines list variable, and output the completed message.

  1. def deleteRecordInformation(id):
  2. newLines = []
  3. file = open(fileName, 'r')
  4. for line in file.readlines():
  5. print (id + " : " + line)
  6. if (line.lower() != id.lower()):
  7. newLines.append(line)
  8. print("wrote")
  9. file.close()
  10. file = open(fileName, 'w')
  11. for line in newLines:
  12. file.write(line + '\n')
  13. print('Completed.')

deleteRecord Function:
This function is similar to the deleteRecordInformation function - in fact, I wrote this function before the deleteRecordInformation function - it simply iterates through each of the lines, adding one on to its custom index variable as it goes, once it gets to the index specified in the arguments parsed to the function, it doesn't write it back.

  1. def deleteRecord(id):
  2. iid = 0
  3. newLines = []
  4. file = open(fileName, 'r')
  5. for line in file.readlines():
  6. if (iid != id):
  7. newLines.append(line)
  8. iid += 1
  9. for line in newLines:
  10. print('Re-writing: ' + str(iid) + " " + line)
  11. iid += 1
  12. iid = 0
  13. file.close();
  14. file = open(fileName, 'w')
  15. for line in newLines:
  16. file.write(line + "\n")
  17. return;

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.