Reputation: 11
I'm trying to write a Login Program in python. I'm trying to read and add the usernames, emails and passwords to a text file. When reading the file I'm using a class to create accounts using the usernames etc. and store them inside my users[] list so I can access it with something like "users[3].username". Everything worked fine but I'm having one problem: When printing the last value of each account (in this case the password) there is an additional empty line. I dont want this because I cant use it like that for example when checking if a password is correct.
This is the code
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", "[email protected]", "1234")
read_accounts()
print(users[0].username)
print(users[0].email)
print(users[0].password)
print("Something")
This is what the Output looks like
Banana
[email protected]
1234
Something
It also happens when dealing wiht multiple accounts and when writing the text file manually instead of using the add_account function. I'm sure the problem is my read_accounts function, because the problem does not occur when creating an account manually like this
account = Accounts("Banana", "[email protected]", "1234")
Also since this is one my firsts programs let me know if you have any other tips.
1 More thing: Originally my post started with "Hey guys" but it got removed. Why does that happen lol?
Upvotes: 0
Views: 43
Reputation: 1415
file.readline()
doesn't strip the newline character from the end of the line, so when you split it up, the newline is still attached to the last element (the password). So you should add an rstrip()
to your reading, e.g.:
x = file.readline().rstrip()
This should help, happy coding!
Upvotes: 1