~ How to edit a specific field in a file in python (e.g. change the password field in a file)


How to edit a specific field in a file in Python

Another task you may be required to tackle is the editing of a field in a file. For instance, perhaps a user changes their password, and it is your job as administrator to edit their password in the stored file. This may sound simple, and it ought to be, but the actual algorithm for doing so in Python with file handling is quite involved. There are various ways of doing it, but the one we look at here is as follows: (and note, you cannot simply do this directly)

When a file like password file is edited, the original file needs to be read into a list, the list needs to be modified (making the password change), and then the new updated list data needs to overwrite the existing file. Note, it is not good practice to overwrite an original file (in reality), so in this case you would be best off creating a temporary file first. The solution here is not necessarily the best, but provides one method for solving this problem, which you will undoubtedly come across

How to edit a specific record in a file in Python (e.g. change a user's password in the file record

Code

""" ==============TASK
ALLOW THE USER TO CHANGE OR EDIT THEIR PASSWORD
1. Search for any given username
2. Edit the password field for that given username
3. Save the new updated username and password to file / updated
"""

#1. This code snippet asks the user for a username and then allows them to change password for that record
    
import csv
def main():

    updatedlist=[]
    temporarylist=[]
    
    with open("fakefacebook.txt",newline="") as f:
      reader=list(csv.reader(f))#convert iterable to a list to make it easier 
      print("CHANGE PASSWORD?!")
      username=input("Enter the username for the required user:")
      temporarylist=reader #store a copy of the data
      
      for row in reader: #for every row in the file
          for field in row:
                if field==username: #if a field is == to the required username
                    updatedlist.append(row) #add each row, line by line, into a list called 'udpatedlist'
                    newpassword=input("Enter new password")
                    updatedlist[0][1] = newpassword #set the field for password to the new password
               
      
      updatepassword(updatedlist,temporarylist)
        
def updatepassword(updatedlist,temporarylist):
    for index, row in enumerate(temporarylist):
        for field in row:
            if field==updatedlist[0]:
                temporarylist[index]=updatedlist #replace old record with updated records

    
    with open("fakefacebook.txt","w",newline="") as f:
        Writer=csv.writer(f)
        Writer.writerows(temporarylist)
        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 ....change password to: BOO123. Note the change below in marvR's record

username,password,email,no_of_likes
marvR,BOO123,[email protected],400
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