~ How to delete a row in a file in python - deleting a row based on user selection of field


How to delete a row in a file in Python based on user selection of a particular field

An obvious scenario that you may have to deal with is having to delete a user record/row from a file. For instance, you may need to specify the username, and then delete that user's whole record. This would involve deleting just one particular row from the file in python. The following code shows you how to do this. Note that it isn't so straightforward as directly deleting the row you want. Consider the algorithm involved as you analyse the code and what it does! See if you can write your own version of something similar but different.

How to delete a user record / single row from a file in Python

Code

""" ==============TASK
1. Search for any given username
2. Delete the whole row for that particular user

e.g.
Enter username: marvR
>>The record for marvR has been deleted from file.
"""

import csv
def main():
    #1. This code snippet asks the user for a username and deletes the user's record from file.
    updatedlist=[]
    with open("fakefacebook.txt",newline="") as f:
      reader=csv.reader(f)
      username=input("Enter the username of the user you wish to remove from file:")
      
      for row in reader: #for every row in the file
            
                if row[0]!=username: #as long as the username is not in the row .......
                    updatedlist.append(row) #add each row, line by line, into a list called 'udpatedlist'
      print(updatedlist)
      updatefile(updatedlist)
        
def updatefile(updatedlist):
    with open("fakefacebook.txt","w",newline="") as f:
        Writer=csv.writer(f)
        Writer.writerows(updatedlist)
        print("File has been updated")
        

main()

File Contents

username,password,email,no_of_likes
marvR,pass123,[email protected],400
smithC,open123,[email protected],200
blogsJ,2bg123,[email protected],99

Output

test data: marvR ....would delete the entire record or row for marvR

username,password,email,no_of_likes
smithC,open123,[email protected],200
blogsJ,2bg123,[email protected],99

Part 2: Ask for the user's name.

Check user's response and respond accordingly. (for instance, responses like: "that's right", or "that's wrong")

Demo of expected solution

Solution Video

Part 3: Validation is important. Validate the user's name entry to allow NO numbers!

You can extend this validation to make it as complex as you like. You could also experiment with additional validation techniques you have come across before. For now, just ensure the user cannot input numbers.

Demo of expected solution

Solution Video

Part 4: Calculate the score - incrementation

What's a quiz without a score? In this part, get the score working. Add +1 to the score every time the user gets an answer right. Ensure the score is added up at the end of the three questions.

Demo of expected solution

Solution Video

Part 5: Put it all in a function called 'quiz'

Modular programming is important. It's quite crucial to have code organised into functions for reasons you have covered in your theory lessons! As you put the existing code into a function, don't forget to get your indentation right.

Demo of expected solution

Solution Video

Part 6: Finally, let's save these names and scores to a text file.

Using the skills that you have already picked up, it shouldn't be too difficult to simply write the name of the user and their score to a text file called scores.txt

Demo of expected solution

Solution Video

All Solution files and answers are in the "Members Only" Box Drive.

Please sign up for more