我正在尝试用 python 编写一个登录程序。我正在尝试读取用户名、电子邮件和密码并将其添加到文本文件中。读取文件时,我正在使用一个类来使用用户名等创建帐户,并将它们存储在我的用户 [] 列表中,以便我可以使用“用户 [3].用户名”之类的内容访问它。一切正常,但我遇到了一个问题:打印每个帐户的最后一个值(在本例中为密码)时,还有一个空行。我不想要这个,因为我不能像那样使用它,例如在检查密码是否正确时。
这是代码
class Accounts:
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
users = []
def add_account(username, email, password):
file = open("useraccounts.txt", "a")
file.write(username + ", " + email + ", " + password + "\n")
file.close()
def read_accounts():
file = open("useraccounts.txt", "r")
count = 0
for line in file:
count += 1
file.seek(0)
for i in range(count):
x = file.readline()
x = x.rsplit(", ")
new_account = Accounts(x[0], x[1], x[2])
users.append(new_account)
file.close()
add_account("Banana", "banana@email.com", "1234")
read_accounts()
print(users[0].username)
print(users[0].email)
print(users[0].password)
print("Something")
这就是输出的样子
Banana
banana@email.com
1234
Something
当处理多个帐户和手动编写文本文件而不是使用 add_account 函数时,也会发生这种情况。我确定问题出在我的 read_accounts 函数上,因为像这样手动创建帐户时不会出现问题
account = Accounts("Banana", "banana@email.com", "1234")
此外,由于这是我的第一个程序,如果您有任何其他提示,请告诉我。
1 更多内容:最初我的帖子以“嘿伙计们”开头,但它被删除了。为什么会这样 哈哈
慕妹3146593
相关分类