How do I delete a specific nickname and password i

2019-09-21 11:46发布

I have difficulties on deleting an account in a text file, although it is a school work.
Here is my code (long and complicated):

create = ""
import time
import sys

while True:
    print("Type create to create, delete to delete")
    acc = input("an account or quit to exit Python: ")
    while acc.lower() == "create":
        found = False
        MinName = 5
        MinPass = 8
        print("Please enter your name.")
        create = input(">").lower()

        if len(create) < MinName:
            print("The name is too short.")
            print("Please enter your name.")
            create = input(">").lower()


        # Open a file
        fi = open("E:/New folder/NO/How about no/accounts.txt", "r")    
        #get the data
        data = fi.readlines()   
        # Close opened file
        fi.close()


        #check each line in the text file
        for li in data:
            #if the name is already in a file
            if(li.split(":")[0].lower() == create):
                #print an error of similar username
                print("Found a similar name, try a different one!")
                #the name has been found
                found = True


        #if the name wasn't found anywhere in the file
        while found == False:
        #ask the user for the password
            passk = input("Your name is OK, enter pasword:\n>")
            if len(passk) < MinPass:
                print("Password must be a minimum of 8 letters.")
                passk = input(">")
                # Open a file to append to
                fi = open("E:/New folder/NO/How about no/accounts.txt", "a")    
                #add the new name/password to the file
                fi.write("\n" + create + ":" + passk)
                # Close opened file
                fi.close()
                print("Created an account. You may now login.")
                sys.exit()

    #Deleting an account##########
    while acc.lower() == 'delete':
        MinName = 5
        MinPass = 8
        print("Please enter your name.")
        delete = input(">").lower()

        if len(delete) < MinName:
            print("The name is too short.")
            print("Please enter your name.")
            delete = input(">").lower()

        fi = open("E:/New folder/NO/How about no/accounts.txt", "r")
        data = fi.readlines()
        fi.close()

        #check each line in the text file
        for li in data:
            #if the name is in a file
            if(li.split(":")[0].lower() == delete):
                #print an text
                print("Found the name.")
                #the name has been found
                found = True

            #Password
                while True:
                    #Set foundpass to false
                    foundpass = False
                    print("Enter your password:")
                    del2 = input(">").lower()

                    if len(del2) < MinPass:
                        print("The password is too short.")
                        print("Please enter your name.")
                        delete = input(">").lower()

                    fi = open("E:/New folder/NO/How about no/accounts.txt", "r")
                    data = fi.readlines()
                    fi.close()

                    for li in data:
                        if(li.split(":")[1].lower() == del2):
                            print("Are you sure you want to delete this account?")
                            delok = input("You may lose all your data (for a long time)! Y/N\n>")
                            if delok.lower() == 'y':
                                file = open("E:/New folder/NO/How about no/accounts.txt", "r")
                                lines = f.readlines()
                                f.close()
                                file = open("E:/New folder/NO/How about no/accounts.txt", "w")
                                for line in lines:
                                    if line != 
                                    sys.exit()

                            elif delok.lower() == 'n':
                                print("Your account is not deleted.")
                                sys.exit()


                    if foundpass == False:
                        print("Incorrect password!")



        #If the name is not in the file
        if found == False:
            print("Incorrect name!")
            delete = input(">").lower()

    if acc.lower() == 'quit':
        break

    else:
        print("This is not an option.")
        time.sleep(1)

The part I need help is:

for li in data:
    if(li.split(":")[1].lower() == del2):
        print("Are you sure you want to delete this account?")
        delok = input("You may lose all your data (for a long time)! Y/N\n>")
        **
        if delok.lower() == 'y':
            file = open("E:/New folder/NO/How about no/accounts.txt", "r")
            lines = f.readlines()
            f.close()
            file = open("E:/New folder/NO/How about no/accounts.txt", "w")
            for line in lines:
                if line !=
                    print("Deleted the account.")
                    sys.exit()
                    **

Deleting a specific line in a file (python)
This is the website I went on but it would only do the nickname I realised. The text file is below:

Name:Password  
aswitneto:llllllll  
madda:mmmmmmmm  

I want to remove both nickname and password.
Any ideas?

1条回答
霸刀☆藐视天下
2楼-- · 2019-09-21 12:08

Okay, it's still horribly flawed (what if there is a ":" in the username or password?), but at least the code is readable:

import os

NAME_MINIMUM_LENGTH = 5
PASSWORD_MINIMUM_LENGTH = 8

ACCOUNTS_FILE = r'C:\temp\accounts.txt' #r'E:/New folder/NO/How about no/accounts_file.txt'
if not os.path.exists(ACCOUNTS_FILE):
    with open(ACCOUNTS_FILE, 'w') as f:
        pass


def main():
    choice = ''
    while choice != 'quit':
        choice = input('\nType "create" to create or "delete" to delete an account. '
                       '"quit" to exit.> ').lower()

        if choice == 'create':
            create_account()

        elif choice == 'delete':
            delete_account()

        elif choice != 'quit':
            print('Sorry, your input is invalid.')


def input_account_name():
    account_name = ''
    while len(account_name) < NAME_MINIMUM_LENGTH:
        account_name = input('Please enter the account name '
                             f'(at least {NAME_MINIMUM_LENGTH} characters)> ')
    return account_name


def input_password():
    password = ''
    while len(password) < NAME_MINIMUM_LENGTH:
        password = input('Please enter a password for the account '
                         f'(at least {PASSWORD_MINIMUM_LENGTH} characters)> ')
    return password


def get_accounts():
    with open(ACCOUNTS_FILE, 'r') as accounts_file:
        accounts = accounts_file.readlines()
    return accounts


def is_available(account_name):
    if any(account_name == str.lower(account.split(':')[0]) for account in get_accounts()):
        return False
    return True


def create_account():
    account_name = input_account_name()
    while not is_available(account_name):
        print('Sorry. This name is already taken. Please try a different one.')
        account_name = input_account_name()

    password = input_password()
    with open(ACCOUNTS_FILE, 'a') as accounts_file:
        accounts_file.write(f'{account_name}:{password}\n')

    print("Created an account. You may now login.")


def delete_account():
    account_name = input_account_name()
    password = input_password()

    accounts = get_accounts()
    if any(f'{account_name}:{password}' == account.strip() for account in accounts):
        if not confirm_deletion():
            print('Nothing was deleted.')
            return

        with open(ACCOUNTS_FILE, 'w') as accounts_file:
            accounts = (a for a in accounts if a.strip() != f'{account_name}:{password}')
            accounts_file.writelines(accounts)
        print('Account deleted.')
    else:
        print('Account unknown or wrong password')


def confirm_deletion():
    confirmation = ''
    while confirmation not in ['y', 'yes', 'n', 'no']:
        confirmation = input(
            'Are you sure you want to delete this account?\n'
            'You will lose all your data – (Y)es or (N)o?> '
        ).lower()
    return confirmation in ['y', 'yes']


if __name__=='__main__':
    main()

What you should learn from above code is not so much how I solved your problem, but how to write clean code. Use proper variable naming and write small reusable functions.

查看更多
登录 后发表回答