我要为我的银行帐户系统提供最后一个功能。
我希望它检查用户名是否已保存到文本文件数据库中。如果用户名已经存在,则应该告诉用户他们不能使用该名称选项。如果没有,那么他们将能够使用它。
我其余的代码可以正常工作,只是fcat无法正确附加/更新文本文件,并查看文本文件数据库中是否已经存在用户名。
import sys
users = {}
status = ""
# Functions ---------------------------------------------------------------------------------------------------------
# Select either account creation or login
def displayMenu():
global status
status = input("Are you a registered user? \n1 - Yes \n2 - No \nQ - Quit \n")
if status == '1':
oldUser()
elif status == '2':
newUser()
else:
print("Unknown input error, exiting . . . .")
sys.exit(0)
return status
# Account creation
def newUser():
global createLogin
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exists
print ("\nLogin name already exists!\n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nAccount created!\n")
#---- Storing the username in a txt file
file = open("accountfile.txt", "a")
file.write(createLogin)
file.write("\n")
file.close()
oldUser()
# Account login
def oldUser():
global login
login = input("Enter login name: ")
passw = input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
file = open("accountfile.txt", "r")
for text in file: ######## This is where I'm trying to compare username duplicates
if text in file == createLogin:
print("Username already exists!")
print("\nLogin successful!\n")
Bank_Account()
else:
print("\nUser doesn't exist or wrong password!\n")
print("Restarting. Please enter details correctly . . . . .")
sys.exit(0)
class Bank_Account:
def __init__(self):
self.balance=0
response = ''
def deposit(self):
try:
amount=float(input("Enter amount to be Deposited: "))
except ValueError:
print("Enter digits only")
else:
self.balance += amount
print("\n Amount Deposited:",amount)
def withdraw(self):
try:
amount = float(input("Enter amount to be Withdrawn: "))
if self.balance>=amount:
self.balance-=amount
print("\n You Withdrew:", amount)
except ValueError:
print("Enter digits only")
s.withdraw()
else:
print("\n ")
def display(self):
print("\n Remaining Balance=",self.balance)
displayMenu()
s = Bank_Account()
# Calling functions with that class object
s.deposit()
s.withdraw()
s.display()
答案 0 :(得分:1)
看起来您正在将用户输入写入文件accountfile.txt
中。因此,在一些用户登录后,它可能类似于:
$ cat accountfile.txt
mike
sarah
morgan
lee
有问题的代码部分在这里:
file = open("accountfile.txt", "r")
for text in file:
if text in file == createLogin:
print("Username already exists!")
这个特定的部分可能没有按照您认为的去做:
if text in file == createLogin
...
if text in file
返回True
或False
。
...
因此,上面的行实际上是在说
if False == createLogin
或
if True == createLogin
我相信您要做的是检查名称是否在accountfile.txt
中。您可以对代码进行的最小更改就是实现
file = open("accountfile.txt", "r")
for text in file:
if text.strip() == createLogin: # .strip() will clean up the \n
print("Username already exists!")
答案 1 :(得分:1)
请尝试对数据库进行酸洗,而不是写入文本文件。 这样可以保存对象的表示形式,您可以轻松地将其加载回程序中。
import pickle
users = {}
users["Ash"] = "password"
pickle.dump(users, open("users.p", "wb"))
loaded_users = pickle.load(open("users.p", "rb"))
print(loaded_users)
更高级的解决方案可能是检出关系数据库,例如[sqlite3] [1]
答案 2 :(得分:1)
此行:
if text in file == createLogin:
是您犯错的地方。该行实质上是在说:
“(如果文本在文件中,则将检查结果与字符串createLogin进行比较”。
即if (True/False) == createLogin
,它总是错误的,因为True / False布尔原语永远不会等于任何字符串(如果它实际运行,我还没有测试是否会抛出异常)。
这是你应该做的
for text in file: # get one line of text
if createLogin == text.strip(): # compare the line with the user input string
print("Username already exists!")
break
.strip()
删除数据库存储名称中的任何前导或结尾空格(在这种情况下,换行符\n
用于表示文件中行的结尾。break
结尾因为找到了要查找的内容,循环过早地完成了查找,因此没有必要继续将用户输入与其他字符串进行比较,假设txt有1000个名称,第一个名称是一个匹配项,则用户会看到错误信息,但该程序将在999次尝试中继续运行,从而使其显得呆滞并浪费不必要的CPU周期。
数据库仍然区分大小写,但是根据您的要求,可能会或可能不会需要。对于不区分大小写的用户,您可以执行以下操作:
for text in file: # get one line of text
if createLogin.lower() == text.strip().lower(): # compare the line with the user input string
print("Username already exists!")
break
.lower()
将两个字符串都变成小写字符串,然后检查它们是否相同,从而消除了大小写敏感性。