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

2 answers

  • answered 2018-03-13 21:46 rahlf23

    This should do the trick (as long as the user is only on a single line, else remove the break statement):

    def delete_usr(usr):
    
        with open("Username.txt","r") as myfile:
            lines = myfile.readlines()
            for idx, l in enumerate(lines):
                if usr==l.split(':')[0]:
                    lines[idx] = ''
                    break
        with open("Username.txt","w") as myfile:
            [myfile.write(i) for i in lines]
    

  • answered 2018-03-13 22:15 gabBGG

    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.