I am trying to make a username and password that gets taken from a text file. The username and password is added at the beginning and used after. I add a username and password at the start and it works. It adds it to the text document but it says that it isn't on the document when i enter the 2 previously created credentials. I put the part i belive is giving issues in **. Any way to make this work properly? If my point isn't clear i can specify more if necessary. Thanks.
import time
import sys
text1 = input("\n Write username ")
text2 = input("\n Write password ")
saveFile = open('usernames+passwords', 'r+')
saveFile.write('\n' + text1 + '\n' + text2 + '\n')
uap = saveFile.read()
saveFile.close()
max_attempts = 3
attempts = 0
while True:
print("Username")
username = input("")
print("Password")
password = input("")
*if username in uap and password in uap:
print("Access Granted")*
else:
attempts+=1
if attempts >= max_attempts:
print(f"reached max attempts of {attempts} ")
sys.exit()
print("Try Again (10 sec)")
time.sleep(10)
continue
break
saveFile.write writes to the end of the file, so the file cursor points to the end of the file.
saveFile.read() reads from the current position to the end (docs).
You need to move the file cursor to the beginning of the file, before reading:
text1 = 'foo'
text2 = 'bar'
saveFile = open('/tmp/usernames+passwords', 'r+')
saveFile.write('\n' + text1 + '\n' + text2 + '\n')
saveFile.seek(0)
uap = saveFile.read()
print(uap)
Out:
foo
bar
Related
I have an issue where when I append to a file, a newline is always added for some reason. This breaks my code. It is meant to be some sort of login system. I have searched for answers alot. Currently I have found the .rstrip('\r'), .strip('\t') and .strip('\n') have not worked.
Example:
I write to a file like this when it already has the contents password1,username1<>:
print("Create")
with open('database.txt', 'a') as database:
username = input("Enter a username: ")
password = input("Enter a password: ")
combined = (password + "," + username + "<>")
combined = combined.strip('\n')
combined = combined.strip('')
combined = combined.strip(' ')
combined = combined.rstrip('\r')
combined = combined.strip('\t')
database.write(combined)
database.close()
#checking total number of users
with open('usernum.txt', 'r+') as usernum:
#the current number + 1 will be the number of the new user
total_num_of_users = usernum.read()
total_num_of_users = int(total_num_of_users) + 1
#incrementing for future numbers
total_num_of_users = str(total_num_of_users)
usernum.truncate(0)
usernum.write(total_num_of_users)
usernum.close()
#making a file containing the users place/number
namefile = str(username) + '.txt'
with open(namefile, 'w+') as usernum:
usernum.write(total_num_of_users)
usernum.close()
Please ignore the fact that the file is called database.txt lol. If my input is username2 and password2 my expected output is:
password1,username1<>password2,username2<>
However instead I get:
password1,username1<>
password2,username2<>
Can anyone help me wth this? Thanks in advance
I'm working on a login system in python atm.
I got so far that I can register a user and create a .txt file with the username and password in two different lines.
textfile
But when it comes to the login system I've run into a problem. I can read the textfile, but when I'm using these two different lines in an if statement using:
try:
#usr is the username given in the login process by the user(the name of the
#created file is always the name of the user)
data = open(usr + ".txt", "r")
l = data.readlines()
#l[0] is reading the first line of code and the iam comparing
#them to the username and password given by the user
if l[0] == usr and l[1] == pss:
print('LOGED IN')
else:
print('WRONG')
except Exception as e:
print('Error reading file')
I am using the latest version of python and I am running on LinuxPopOs
my whole code:
import time
print("LOGIN -> 1")
print("Register -> 2")
print("")
select_ = input("")
if select_ == '2':
print("Username:")
usernamee = input()
print("Password:")
passworde = input()
print("Type ""y"" to register or ""n"" to cancel")
forward = input("")
if forward == 'y':
#creating database
data = open(usernamee + ".txt", "w")
data.write(usernamee + "\n")
data.write(passworde)
data.close()
else:
print('closing...')
time.sleep(2)
exit(0)
elif select_ == '1':
print("LOGIN:")
usr = input("Username:")
pss = input("Password:")
try:
#usr is the username given in the login process by the user
data = open(usr + ".txt", "r")
l = data.readlines()
#l[0] is reading the first line of code and the iam comparing
#them to the username and password given by the user
if l[0] == usr and l[1] == pss:
print('LOGED IN')
else:
print('WRONG')
except Exception as e:
print('Error reading file')
else:
print(select_ + "is not valid")
Thanks
The problem appears to be that white space and/or newline characters aren't being stripped from the strings read by readline. Changing the if statement to strip trailing characters should rectify that, e.g. if l[0].rstrip() == usr and l[1].rstrip() == pss:
So I'm making a python script where you can create an account and that account is saved in a text file. When you try to log in, it will look in the text file for your username and then move down a line for the password but I don't know how to move down a line after finding the username. Any help would be appreciated. :)
Update -
import time
import sys
print ("Do you have an account?")
account = input()
if account == "Yes":
print ("Enter your username")
enterUsername = input()
with open ("Allusers.txt") as f:
if enterUsername in f.read():
print ("Enter your password")
enterpassword = input()
if enterpassword in f.read():
print ("Logged in")
if enterpassword not in f.read():
print ("Wrong password")
if account == "No":
print ("Create a username")
createUsername = input()
with open ("Allusers.txt") as f:
if createUsername in f.read():
print ("Username already taken")
sys.exit()
if createUsername not in f.read():
print ("Create a password")
createPassword = input()
with open ("Allusers.txt") as f:
if createPassword in f.read():
print ("Password not available")
sys.exit()
if createPassword not in f.read():
file_object = open ('Allusers.txt', 'a')
file_object.write("" + createUsername + "\n")
file_object.close()
file_object = open ('Allusers.txt', 'a')
file_object.write("" + createPassword + "\n")
file_object.close()
print ("Done")
This is still work in progress and most likely still has errors here and there.
Assumin that your file look like this:
Adam
password
John
12345678
Horacy
abcdefg
Romek
pass1234
You can try this example:
user = "Horacy"
password = "abcdefg"
with open( "users.txt", "r" ) as file:
for line in file:
if user == line.strip():
if password == file.readline().strip():
print( "Correct" )
break
As stated if someones password equals someones username iterating over all lines and checking may return faulty results you'll want to check only usernames as you iterate, so zipping every other line you can check the username only and return the password:
def get_password(file, username):
with open(file, "r") as f:
data = f.readlines()
for user, pw in zip(data[::2], data[1::2]):
if user.strip() == username:
return pw.strip()
def get_password(file, username):
lines = open(file, "r").readlines() # get the lines from the file
for i, line in enumerate(lines):
if line == username: # if the current is the username, return the following line
return lines[i + 1]
You should only search in usernames. The data[::2] will select usernames.
with open("filename", "r") as f:
data = f.read().splitlines()
email = "email#email"
if email in data[::2]:
id_email=data[::2].index(email)
row=id_email*2-1
password=data[row+1]
ive been searching for ages for a solution on my problem:
When a user types in a name, which is already saved in a .txt file, it should print "true".
If the username is not already existing it should add the name, the user typed in.
The Problem is, that it even prints out true when the typed name is "Julia", but "Julian" is already in the list. I hope you get my point.
I already read maaany solutions here on stackoverflow but nothing worked for me when working with a .txt file
My code:
import mmap
username = input("username: ")
names_file = open("names_file.txt", "a")
paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(paste) != -1:
print("true")
else:
names_file.write("\n" + username)
print(username + " got added to the list")
names_file.close()
username = input("username: ")
found = False
with open("names_file.txt", "r") as file:
for line in file:
if line.rstrip() == username:
print("true")
found = True
break
if not found:
with open("names_file.txt", "a") as file:
file.write( username + "\n")
print(username + " got added to the list")
You could add the newline after the name and search for the name with the newline character:
import mmap
username = input("username: ")
names_file = open("names_file.txt", "a")
paste = bytes('\n' + username + '\n', 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(paste) != -1:
print("true")
else:
names_file.write('\n' + username + '\n')
print(username + " got added to the list")
names_file.close()
This will not work for names with spaces inside -- for such cases you'll have to define different separator (also if all names begin with a capital letter and there are no capital letters in the middle of the name then you could spare the newline before the name)
Try this i have updated my answer.
import mmap
import re
status = False
username = input("username: ")
names_file = open("names_file.txt", "a")
paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
for f in file:
f = f.strip()
if f == paste:
print("true")
status = True
if status == False:
names_file.write("\n" + username)
print(username + " got added to the list")
names_file.close()
I have a text file which contents the credentials to access a my app, example off my text file
#cat /etc/app/paswords
petter#domain.com $8324dhedberhnnhdbcdhgvged
userhappy#domain.com $2349cmjedcnecbcdfrfrrf8839
the spaces are tab's
I want to change the password hash or the complete line whith a new password
I have the following code:
#cat passreplace.py
domain = "midomain.com"
user = "userhappy"
email = user + "#" + domain
print email
if email in open('/etc/app/passwords').read():
print "User already exist!! one moment change your password"
#code to remplace password
thank you
fileinput is a good choice for this one.
import fileinput
email = username + password
for line in fileinput.input('/etc/app/passwords', inplace=True):
if email in line:
print("User already exists! Change password now!")
username,password = line.split('\t')
old_pass = input("Enter old password: ")
if old_pass != password:
# do something
new_pass = input("Enter new password: ")
confirm = input("Confirm new password: ")
if new_pass != confirm:
# do something
print("\t".join([email, new_pass]), end="")
else:
print(line, end="")