Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何删除文本文件中的特定昵称和密码?_Python_Python 3.x_Text Files - Fatal编程技术网

Python 如何删除文本文件中的特定昵称和密码?

Python 如何删除文本文件中的特定昵称和密码?,python,python-3.x,text-files,Python,Python 3.x,Text Files,我在删除文本文件中的帐户时遇到困难,尽管这是一项学校作业。 这是我的代码(长而复杂): 这是我的网站,但它只会做我意识到的昵称。文本文件如下: 我想删除昵称和密码 有什么想法吗?好吧,它仍然有严重的缺陷(如果用户名或密码中有“:”怎么办?),但至少代码是可读的: import os NAME_MINIMUM_LENGTH = 5 PASSWORD_MINIMUM_LENGTH = 8 ACCOUNTS_FILE = r'C:\temp\accounts.txt' #r'E:/New fol

我在删除文本文件中的帐户时遇到困难,尽管这是一项学校作业。
这是我的代码(长而复杂):


这是我的网站,但它只会做我意识到的昵称。文本文件如下:

我想删除昵称和密码

有什么想法吗?

好吧,它仍然有严重的缺陷(如果用户名或密码中有“:”怎么办?),但至少代码是可读的:

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()
导入操作系统
名称\最小\长度=5
密码\最小\长度=8
ACCOUNTS_FILE=r'C:\temp\ACCOUNTS.txt'#r'E:/New folder/NO/NO/ACCOUNTS_FILE.txt怎么样'
如果不存在os.path.exists(ACCOUNTS\u文件):
打开(账户_文件,'w')作为f:
通过
def main():
选择=“”
而选择退出':
选择=输入('\n键入“创建”以创建帐户,或键入“删除”以删除帐户。'
““退出”退出。>”)。降低()
如果选项==“创建”:
创建_帐户()
elif choice==“删除”:
删除_账户()
伊里夫选择!='退出':
打印('对不起,您的输入无效')
def input_account_name():
帐户名称=“”
而len(账户名称))
返回帐户名
def input_password():
密码=“”
而len(密码))
返回密码
def get_帐户():
打开(帐户\u文件,'r')作为帐户\u文件:
accounts=accounts\u file.readlines()
返回帐户
def可用(帐户名称):
如果get_accounts()中的帐户有(account_name==str.lower(account.split(':')[0]):
返回错误
返回真值
def create_account():
账户名称=输入账户名称()
不可用时(帐户名称):
打印('抱歉,此名称已被使用。请尝试其他名称。')
账户名称=输入账户名称()
密码=输入密码()
将打开的(帐户文件“a”)作为帐户文件:
accounts\u file.write(f'{account\u name}:{password}\n')
打印(“已创建帐户。您现在可以登录。”)
def delete_帐户():
账户名称=输入账户名称()
密码=输入密码()
accounts=get_accounts()
如果有(f'{account\u name}:{password}'==account.strip(),用于accounts中的account):
如果未确认删除():
打印('未删除任何内容')
返回
打开(帐户\u文件,'w')作为帐户\u文件:
accounts=(如果a.strip()!=f'{account_name}:{password}',则a代表帐户中的a)
账户\文件写入行(账户)
打印('帐户已删除')
其他:
打印('帐户未知或密码错误')
def确认_删除():
确认=“”
当确认不在['y'、'yes'、'n'、'no']中时:
确认=输入(
'确实要删除此帐户吗?\n'
'您将丢失所有数据–(是)或(否?>'
).lower()
以['y','yes'格式返回确认函
如果“名称”=“\uuuuuuuu主要”:
main()
您应该从上面的代码中学到的不是我如何解决您的问题,而是如何编写干净的代码。
使用适当的变量命名并编写小型可重用函数。

是否一次删除三行?顺便说一句,有很多更简单的方法来做你想做的事情-你可能想研究像SQLite这样的东西,这是一个学习曲线,但从长远来看可能会让你省去一些麻烦!阅读如何创建。我不想同时删除多行,我需要一个代码来删除文本文件中用户想要删除其登录帐户的一行。@PeterWood谢谢,我现在就阅读它。
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()
                    **
Name:Password  
aswitneto:llllllll  
madda:mmmmmmmm  
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()