Text file clearing itself when program is run again - python

I made a program that allows the user to create an account. It seemed to work until I tried the login feature, which kept alerting me that the username and password do not exist. When I re-run the program and create an account, the txt file has my given name and password inside. However when I close the program and reopen it to run the login feature the name and password are no longer there. Any ideas on how to fix this?
PS: I'm rather new to all of this and if there is anything i could/should have done instead please let me know.
while True:
#Account file and same file as list.
AccountsFile = open("AccountProj.txt", "w+")
AccountList = [line.split(',') for line in AccountsFile.readlines()]
#Creates an account
def createaccount():
while True:
newname = (input("Please create a username: "))
if newname in AccountsFile:
print("Username already in use.")
continue
elif newname not in AccountsFile:
newpassword = input("Please create a password: ")
checkpassword = input("Re-enter password: ")
if checkpassword == newpassword:
print("Account Sucessesfuly created!")
AccountsFile.write(newname + "\n")
AccountsFile.write(checkpassword + "\n")
AccountsFile.close()
break
elif checkpassword != newpassword:
print("Passwords do not match")
continue
#Logs into an account
def loginaccount():
while True:
username_entry = input("Enter username: ")
if username_entry not in AccountList:
print("Username not found. Please enter a valid name")
continue
elif username_entry in AccountList:
password_entry = input("Enter password: ")
if password_entry in AccountList[AccountList.index(username_entry) + 1]:
print("Login sucessful!")
AccountsFile.close()
break
if password_entry not in AccountList[AccountList.index(username_entry) + 1]:
print("Username and password do not match. Please try again.")
AccountsFile.close()
continue
#Asks if user wants to create or login to an account
loginchoice = input("Would you like to login? (Y/N) ")
if loginchoice in ('Y', 'N'):
if loginchoice == 'Y':
loginaccount()
if loginchoice == 'N':
createchoice = str(input("Would you like to create an account? (Y/N) "))
if createchoice in ('Y', 'N'):
if createchoice == 'Y':
createaccount()
if createchoice == 'N':
exit()
break
else:
print("Invalid Input")

You opened your file in w+ mode, this will override your previous content because it starts writing right at the beginning of the file.
Instead, you should use the a mode for appending your text to any previously written content.
See: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files:
(...) mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end.

Related

My script can't recognise names inside the username file

It can see the file, if i change the name on the path slightly run seizes to function but eithr way it can't read the words in the file despite being able to before while I was writing the program. And now suddenly it doesn't work, the file location is the same and all.
P.S. I have no idea how to specify code on overflow
filen = 'C:\Users\fabby\Documents\Extra Things I Might Need\Port Folio Stuff\Python\usernames'
usern = open(filen, 'r')
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
def func():
user = input("Enter new Username: ")
passs = input("Enter new Password: ")
passs1 = input("Confirm password: ")
if passs != passs1:
print("Passwords do not match!")
else:
if len(passs) <= 6:
print("Your password is too short, restart:")
elif user in usern:
print("This username already exists")
else:
usern = open(filen, "a")
usern.write(user+", "+passs+"\n")
print("Success!")
while True:
if userr not in usern:
again = input("This username does not exist, would you like to try again? ")
if again == ("No"):
func()
elif again == ("no"):
func()
elif again == ("Yes"):
print("Try again:")
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
elif again == ("yes"):
print("Try again:")
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
elif userr in usern:
print("Good, you have entered the zone")
I am not sure I have full understand your means, but as your code, I have some suggestions:
close file if you open it
use f.readline() and str.split() to parse username and passwd and store in array, so you can use in to check, if the file is not to large.

i am having trouble with open() command in python

I am currently developing a desktop login-register app for my practice, and was having some trouble with login and register. If I type REGISTER and add my info in f.write() command it stores my info but after that everything just goes, like the whole file gets formatted (this was register issue).
The login issue is if I want to check whether a name or password in file exists or not (this command could be wrong). I tried to use if login_email and login password in f: but it says that login_email and password do not exist.
Code:
f = open('pass.txt', 'w')
fr = open('pass.txt', 'r')
from time import sleep
login_list = "LOGIN"
register_list = "REGISTER"
if 1 > -3232:
print("Type register for new account\ntype login for login into existing account")
bi = input("==> ")
if bi.upper() in login_list:
print("you are registered?? nice now loginnn!!")
login_1 = input("your username: ")
login_2 = input("your password: ")
if login_1 and login_2 in fr:
print("Nice my program worked??")
exit()
else:
exit()
elif bi.upper() in register_list:
print("you are in register section: ")
sleep(.9)
print("NOTE: Your password should only contain alphabets!")
sleep(4)
reg_1 = input("your username: ")
sleep(.9)
reg_2 = input("your password: ")
sleep(.9)
reg_2v1 = input("confirm password")
if reg_2 == reg_2v1:
f.write(reg_1 + " : " + reg_2 + "\n")
print("now login again,\")
else:
print("invalid password, try again")
else:
print("you gave me the wrong command")
else:
exit()
You shouldn't open the file in both read and write mode at the beginning of the script. Opening it in write mode empties the file, so you won't be able to read it. You'll also wipe out all the other usernames and passwords. You should open the file in read mode when logging in, and append mode when registering, to add a new line without removing the old ones. And you should use with to just open the file around the code that needs to use it.
if login_1 and login_2 in fr: is not the correct way to test if both the username and password are in the file. Due to operator precedence, that's parsed as if login_1 and (login_2 in fr):. This just checks that login_1 is not empty, and then just checks if login_2 is in the file. The second test will never work, because the lines of the file all end with newline, but login_2 doesn't, so they'll never match.
You need to check for the fully formatted line, including the newline.
if f'{login_1} : {login_2}\n' in fr:
if bi.upper() in login_list: seems suspicious. login_list is not a list, it's a string. So this will check whether bi.upper() is any substring -- it will succeed if the user enters log or in or gi, not just login. Is that intentional?
Full code:
from time import sleep
login_list = "LOGIN"
register_list = "REGISTER"
if 1 > -3232:
print("Type register for new account\ntype login for login into existing account")
bi = input("==> ")
if bi.upper() in login_list:
print("you are registered?? nice now loginnn!!")
login_1 = input("your username: ")
login_2 = input("your password: ")
with open('pass.txt', 'r') as fr:
if f'{login_1} : {login_2}\n' in fr:
print("Nice my program worked??")
exit()
else:
exit()
elif bi.upper() in register_list:
print("you are in register section: ")
sleep(.9)
print("NOTE: Your password should only contain alphabets!")
sleep(4)
reg_1 = input("your username: ")
sleep(.9)
reg_2 = input("your password: ")
sleep(.9)
reg_2v1 = input("confirm password")
if reg_2 == reg_2v1:
with open('pass.txt', 'a') as f:
f.write(reg_1 + " : " + reg_2 + "\n")
print("now login again,")
else:
print("invalid password, try again")
else:
print("you gave me the wrong command")
else:
exit()

Account creation program is not reading file properly

I've been making a program that allows the user to create an account which saves to a txt file, and allows them to login. The text now saves to the file (which I was unable to make work earlier due to using w+ instead of a+) but I am not quite sure I understand how split() works. When I try to use the info saved to the txt file the program returns that the username cannot be found. If anyone could fix this code id appreciate it.
I began a few weeks ago so a lot of this is new to me.
AccountsFile = open("AccountProj.txt", "a+")
AccountList = [line.split('\n') for line in AccountsFile.readlines()]
#Creates an account
def createaccount():
while True:
newname = (input("Please create a username: "))
if newname in AccountsFile:
print("Username already in use.")
continue
elif newname not in AccountsFile:
newpassword = input("Please create a password: ")
checkpassword = input("Re-enter password: ")
if checkpassword == newpassword:
print("Account Sucessesfuly created!")
AccountsFile.write(newname + '\n')
AccountsFile.write(checkpassword + '\n')
AccountsFile.close()
break
elif checkpassword != newpassword:
print("Passwords do not match")
continue
#Logs into an account
def loginaccount():
while True:
username_entry = input("Enter username: ")
if username_entry not in AccountList:
print("Username not found. Please enter a valid name")
continue
if username_entry in AccountList:
password_entry = input("Enter password: ")
if password_entry in AccountList[AccountList.index(username_entry) + 1]:
print("Login sucessful!")
AccountsFile.close()
break
if password_entry not in AccountList[AccountList.index(username_entry) + 1]:
print("Username and password do not match. Please try again.")
AccountsFile.close()
continue
while True:
#Asks if user wants to create or login to an account
loginchoice = input("Would you like to login? (Y/N) ")
if loginchoice in ('Y', 'N'):
if loginchoice == 'Y':
loginaccount()
if loginchoice == 'N':
createchoice = str(input("Would you like to create an account? (Y/N) "))
if createchoice in ('Y', 'N'):
if createchoice == 'Y':
createaccount()
if createchoice == 'N':
pass
break
else:
print("Invalid Input")
def CreateAccount():
Username = input("Username: ") #Enter Username
Username.replace(" ", "") #Removes spaces (Optional)
AppValid = True #Default value that changes if duplicate account found
File = open("Accounts.txt","r") #Checking if username already exits
for Line in File:
Account = Line.split(",")
if Account[0] == Application:
print("There is already an Account with this Username")
AppValid = False #Changing value if username exits
File.close()
if AppValid == True: #If username not found, carries on
Password = input("Password: ") #Asks for Password
CheckPassword = input("Password: ")
if Password == CheckPassword:
print("Password's Match!") #Password Match
else:
print("No match")
File = open("Accounts.txt","a") #Writing new account to File
File.write(Username + "," + Password + "\n")
File.close()
def ViewAccount(Username, Password):
File = open("Accounts.txt","r")
Data = File.readlines()
File.close()
if len(Data) == 0:
print("You have no Accounts") #Account not found since no accounts
else:
AccountFound = false
for X in Data: #Looping through account data
if X[0] == Username: #Username match
if X[1] == Password:
AccountFound = true
print("Account Found")
if AccountFound = false:
print("Account not FOUND")
Theres some code i threw together (JK my hand hurts from typing that and my keyboard is screaming) but back to the point .split(" ") would split a string into a list based on spaces for that example, eg:
String = "Hello There"
String = String.split(" ") #Or String.split() only owrks for spaces by default
print("Output:", String[0]) #Output: Hello
print("Output:", String[1]) #Output: There
String = "Word1, Word2"
String = String.split(", ") #Splits string by inserted value
print("Output:", String[0]) #Output: Word1
print("Output:", String[1]) #Output: Word2
String = "abcdefghijklmnop"
String = String.split("jk") #Splits string by inserted value
print("Output:", String[0]) #Output: abcdefghi
print("Output:", String[1]) #Output: lmnop
Check AccountList - both split() and readlines() create a list for you, so you have a list of lists and your username_entry check can't work that way.

python read/write to file login script

I was wondering if anyone would help. I am new to python. I am trying to create a basic login script for a game, that will write a username and password to a text file. When logging in, it will read from that text file and compare the entry made by the user. The code is below:
def Register():
print("Hello! You need to register an account before you can begin")
username = input("Please enter a username: ")
password = input("Now please enter a password: ")
file = open("Login.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
print ("Your login details have been saved. ")
print("You will now need to login")
Login()
def Login():
print("Please enter your details to log in")
username1 = input("Please enter your username: ")
password1 = input("Please enter your password: ")
file = open("Login.txt","r")
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
print(username,password)
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
#file.close()
user=input("Are you already a user? ")
if user == "Yes":
Login()
elif user =="No":
Register()
print("Welcome to our game")
I have entered the second user who is stored in the text file, It seems to be working but it checks my first entry and says its incorrect and then loops to the second entry. This is the output I keep getting:
Are you already a user? Yes
Please enter your details to log in
Please enter your username: jen
Please enter your password: ben
tess bess
incorrect
jen ben
Hello jen
Welcome to the dice game
>>>
Does anyone have an idea on how to only display the entry you have entered?
Thanks
Like Sharku said, put the print(username,password) in your if below. Also writting clearly the name and password of the user after he typed it isn"t really a smart moove, delete it and just let your message when a user is logging in !
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
As said by sytech, you could use the break and else clauses of the for loop:
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
break
else:
print("incorrect")
Your 'for loop' will loop through each entry in your file, that means for each entry in the file your for loop prints the entry due to this line:
print(username,password)
If you don't want it to print all values in the file remove this line of code.
Adding a 'break' to your if statement, as suggested by others, will mean that as soon as your loop has found the entry that matches the one entered by the user it will leave the loop and not continue going through all values unnecessarily.
You could do something like this:
if username1 == username and password1 == password:
print("Hello",username)
break
else:
continue
This means that when a user input doesn't match an entry in the file the loop will just continue till it finds a match.
However, your code doesn't take into consideration if a user doesn't exist.
import os.path
if not os.path.exists('register.txt'):
file = open('register.txt', 'w')
file.close()
def register():
username = input('Enter username: ')
if username in open('register.txt', 'r').read():
print('Username already exists')
exit()
password = input('Enter password: ')
c_password = input('Enter confirm password: ')
if password != c_password:
print('Sorry password not match')
exit()
handle = open('register.txt', 'a')
handle.write(username)
handle.write(' ')
handle.write(password)
handle.write('\n')
handle.close()
print('User was successfully registered')
exit()
def login():
username = input('Enter username: ')
password = input('Enter password: ')
get_data = open('register.txt', 'r').readlines()
users_data = []
for user in get_data:
users_data.append(user.split())
total_user = len(users_data)
increment = 0
login_success = 0
while increment < total_user:
usernames = users_data[increment][0]
passwords = users_data[increment][1]
if username == usernames and password == passwords:
login_success = 1
increment += 1
if login_success == 1:
print('Welcome ' + username)
else:
print('invalid username & password')
question = input('Do you have an account?/yes/no')
if question == 'yes':
login()
else:
register()

How can i create a login with a text file

So I've been trying to create a quiz where you have to have an account which means you can register and login. I managed to code the register part(which i'm pretty proud of) and it saves the login details to a separate text file, when it saves the login details it looks like this: username:password
Now i'm struggling with the login part, I think you have to read the text file and then split the username and password, then I some how have to compare the inputted username and password to the saved ones.
This is what I done for the login part so far but it doesn't work:
def login():
filename = 'Accounts.txt'
openfile = open('Accounts.txt', "r")
Userdata = openfile.readlines()
with open('Accounts.txt', 'r') as file:
for line in file:
user2, passw = line.split(':')
login2 = input("Enter username: ")
passw2 = input("Enter passwordd: ")
if login2 == user2 and passw2 == passw:
print("Logged in")
else:
print("User or password is incorrect!")
openfile.close();
Now this is how the whole code looks like(if needed):
import time
print("Welcome to my quiz")
#Creating username
def create():
print ("We will need some information from you!")
time.sleep(1)
Veri = input("Would you like to continue (yes or no): ")
def createAccount():
while True:
name = input("Enter your first name: ")
if not name.isalpha():
print("Only letters are allowed!")
else:
break
while True:
surname = input("Enter your surname: ")
if not surname.isalpha():
print("Only letters are allowed!")
else:
break
while True:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Only numbers are allowed!")
continue
else:
break
if len(name) >= 3:
username = name[0:3]+str(age)
elif len(surname) >= 3:
username = surname[0:3]+str(age)
else:
username = input("Create a username: ")
print ("Your username is:",username)
while True:
password = input("Create a password: ")
password2 = input("Confirm your password: ")
if password != password2:
print("Password does not match!")
else:
break
account = '%s:%s\n'%(username,password)
with open ('Accounts.txt','a') as file:
file.write(account)
print ('Account saved')
if Veri == 'no':
menu()
elif Veri == 'yes':
createAccount()
else:
print ("Sorry, that was an invalid command!")
time.sleep(1)
login()
#Loging in
def login():
filename = 'Accounts.txt'
openfile = open('Accounts.txt', "r")
Userdata = openfile.readlines()
with open('Accounts.txt', 'r') as file:
for line in file:
user2, passw = line.split(':')
login2 = input("Enter username: ")
passw2 = input("Enter passwordd: ")
if login2 == user2 and passw2 == passw:
print("Logged in")
else:
print("User or password is incorrect!")
openfile.close();
time.sleep(1)
#Choosing to log in or register
def menu():
LogOrCre = input("Select '1' to login or '2' to register: ")
if LogOrCre == '1':
login()
elif LogOrCre == '2':
create()
else:
print ("Sorry, that was an invalid command!")
menu()
menu()
If you have any ideas on how I can make the login part, that would be helpful.
You are asking for the user's username and password for every line in the accounts file. Get the inputted login information outside of the for loop.
Welcome to programming!
It can be very daunting, but keep studying and practicing. You are in the right way!
I see some points in your code that could be improved. I'm commenting below:
1) You don't need to use both open() (and close()) and with to access a file's contents. Just use with, in this case. It will make you code simpler. (A good answer about with)
2) You're asking for the user login & passwd inside a loop (aka multiple times). It can be very annoying for your user. Move the input's call to before the for loop.
3) You also need to break the loop when the login succeeds.
So, a slightly improved version of your code would be:
filename = 'Accounts.txt'
with open(filename, 'r') as file:
login2 = input("Enter username: ")
passw2 = input("Enter password: ")
for line in file:
user2, passw = line.split(':')
if login2 == user2 and passw2 == passw:
print("Logged in")
break
else:
print("User or password is incorrect!")
Not sure what is not working in your code, but I updated the code as below and was able to print logged in.
def login():
#filename = 'Accounts.txt'
#openfile = open('Accounts.txt', "r")
#Userdata = openfile.readlines()
with open('Accounts.txt', 'r') as file:
login2 = input("Enter username: ")
passw2 = input("Enter passwordd: ")
for line in file:
user2, passw = line.split(':')
if login2 == user2 and passw2 == passw:
print("Logged in")
break
else:
continue
login()

Categories

Resources