尽管这是学校的工作,但我在文本文件中删除帐户时遇到了困难。
这是我的代码(又长又复杂):
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)
我需要帮助的部分是:
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)
这是我继续经营的网站,但只会使用我意识到的昵称。文本文件如下:
Name:Password aswitneto:llllllll madda:mmmmmmmm
我要同时删除昵称和密码。
有什么想法吗?
答案 0 :(得分:0)
好的,它仍然存在严重缺陷(用户名或密码中是否有“:”?),但至少代码是可读的:
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()
您应该从上述代码中学到的不是我如何解决您的问题,而是如何编写简洁的代码。 使用适当的变量命名并编写小的可重用函数。