I have the following code, that goes through the stages of reading a file in line by line, converting it into a list, editing a field in that list, but the last stage is rewriting the original file, with this edit included.
I would be interested in answers that suggest the easiest/simplest fix (without the use of pandas/numpy etc) and using the original code provided.
My current algorithm includes having to create a new file with all the records, except the one linked to this username, and then writing in this list to it. This seems arduous and unnecessary. Any solutions gratefully received!
The task is explained more clearly in the comments:
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
"""
import csv
def main():
#1. This code snippet asks the user for a username and then allows them to change password for that record
updatedlist=[]
with open("fakefacebook.txt",newline="") as f:
reader=csv.reader(f)
print("CHANGE PASSWORD?!")
username=input("Enter the username for the required user:")
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")
#print(updatedlist[0][1]) (this is how we get at the password field, noting it is a nested list)
updatedlist[0][1] = newpassword #set the field for password to the new password
updatepassword(updatedlist)
def updatepassword(updatedlist):
with open("fakefacebook.txt","w",newline="") as f:
Writer=csv.writer(f)
Writer.writerows(updatedlist)
print("File has been updated")
main()
Note: at the moment the code just allows the user to change password (and this is changed in the list). The list is comprised of just that user's record. It overwrites this single record (with the changed password) to the text file, instead of what is required (original file contents + just this edit)
File Contents
username,password,email,no_of_likes
marvR,pass123,marv@gmail.com,400
smithC,open123,cart@gmail.com,200
blogsJ,2bg123,blog@gmail.com,99
Required output
If tested with: marvR change password to: boo123
new file should contain:
username,password,email,no_of_likes
marvR,**boo123**,marv@gmail.com,400
smithC,open123,cart@gmail.com,200
blogsJ,2bg123,blog@gmail.com,99
Any comments/explanations about the best way to approach this for teaching beginners would also be appreciated. It seems odd that Python hasn't developed a module of some sort to make editing a field in a file easier than this 3 step algorithm which is really quite arduous for beginners (i'm talking 13-14 year olds) to work out