我正在嘗試用 python 編寫一個登錄程序。我正在嘗試讀取用戶名、電子郵件和密碼并將其添加到文本文件中。讀取文件時,我正在使用一個類來使用用戶名等創建帳戶,并將它們存儲在我的用戶 [] 列表中,以便我可以使用“用戶 [3].用戶名”之類的內容訪問它。一切正常,但我遇到了一個問題:打印每個帳戶的最后一個值(在本例中為密碼)時,還有一個空行。我不想要這個,因為我不能像那樣使用它,例如在檢查密碼是否正確時。這是代碼class Accounts: def __init__(self, username, email, password): self.username = username self.email = email self.password = passwordusers = []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", "[email protected]", "1234")read_accounts()print(users[0].username)print(users[0].email)print(users[0].password)print("Something")這就是輸出的樣子[email protected]當處理多個帳戶和手動編寫文本文件而不是使用 add_account 函數時,也會發生這種情況。我確定問題出在我的 read_accounts 函數上,因為像這樣手動創建帳戶時不會出現問題account = Accounts("Banana", "[email protected]", "1234")此外,由于這是我的第一個程序,如果您有任何其他提示,請告訴我。1 更多內容:最初我的帖子以“嘿伙計們”開頭,但它被刪除了。為什么會這樣 哈哈
1 回答
慕妹3146593
TA貢獻1820條經驗 獲得超9個贊
file.readline()不會從行尾刪除換行符,因此當您將其拆分時,換行符仍附加到最后一個元素(密碼)。所以你應該在rstrip()你的閱讀中添加一個,例如:
x = file.readline().rstrip()
這應該有所幫助,編碼愉快!
添加回答
舉報
0/150
提交
取消
