input in a function and remove lines from a file
I'm trying to make a modules and for one of the commands I need it to remove a specified user. I need help with it finding the line the user is at. Then deleting the username. Here is the code.
def delete_usr(usr): file = open("Username.txt","r+") count = 0 userfound = False try: for user in file.readlines(): count += 1 if usr == user.strip(): userfound = True
BTW i also need it to delete the password. The password has the same line as the username and is kept in password.txt
This should do the trick (as long as the user is only on a single line, else remove the
def delete_usr(usr): with open("Username.txt","r") as myfile: lines = myfile.readlines() for idx, l in enumerate(lines): if usr==l.split(':'): lines[idx] = '' break with open("Username.txt","w") as myfile: [myfile.write(i) for i in lines]
The closest solution to your suggestion would be:
def delete_usr(usr): file = open("Username.txt","r+") count = 0 userfound = False for user in file.readlines(): #print(user.strip()) count += 1 if usr == user.strip(): userfound = True #print("yeah") #break file.close()
If you use a try statement, you expect a perticular kind of error (eg. key not in a dictionary) and also should write except statement to catch the error. If you use open(file), it is a good practice to also use file.close(). If you use the with statement, as in the example above, you don't need to do it as it is done automatically.