Python validate input against text file - python

file=open('New Text Document.txt','w')
lines=file.writelines(['username:ds_jr\n','password:89120&%'])
file.close()
file=open('New Text Document.txt','r')
file.readlines()
username=input('username:')
password=input('password:')
check=['username:'+username+'\n','password:'+password]
if check == lines:
print('hello ds_jr , welcome!')
else:
print('not found')
How to compare input username and password against .txt file content.

file=open('New Text Document.txt','w')
lines=file.writelines(['username:ds_jr\n','password:89120&%'])
file.close()
username=input('username:')
password=input('password:')
file = open('New Text Document.txt')
check = file.read()
if username and password in check:
print('hello ds_jr , welcome!')
else:
print('not found')

Lookups in Python are best implemented in dictionaries. Dictionaries can also be useful for holding the information that you want to write into the file. In this case there are only two values but for flexibility let's put those into a dictionary to begin with.
Choose a format for the file that can be understood later when reading.
When the file is read, build a new dictionary to store the keywords and values.
Now you can get the user input and check the values entered against the new dictionary.
FILE = 'New Text Document.txt'
USERNAME = 'username'
PASSWORD = 'password'
out_d = {USERNAME: 'ds_jr', PASSWORD: '89120&%'}
with open(FILE, 'w') as f:
for k, v in out_d.items():
print(f'{k}={v}', file=f)
in_d = dict()
with open(FILE) as f:
for line in map(str.strip, f):
if (eq := line.find('=')) >= 0:
in_d[line[:eq]] = line[eq+1:]
username = input(f'{USERNAME}: ')
password = input(f'{PASSWORD}: ')
if username == in_d.get(USERNAME) and password == in_d.get(PASSWORD):
print("You're good to go")
else:
print('Incorrect username or password')
Now let's say that you want to keep more information in the file. All you have to do is edit the in_d dictionary appropriately with no need to make any other modifications to the code

Related

How do I select certain lines in a text file from python script?

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]

How to save a variable to a text file and retrieve it later?

I am trying to make a program to save passwords. How do I take the input and put it into a text file password.txt? Also how would I retrieve that data in the future and print it out?
def display():
print ("Do you want to add a password to get a password? get/add")
response = input()
if response == "get":
savingPasswords()
def savingPasswords():
username = input("Enter username")
username = open ('password.txt', 'w')
password = input ("Enter password")
account = input("What account is this for?")
print ("Login successfully saved!")
while status == True:
display()
you can store your data as a json:
import json
import os
# data will be saved base on the account
# each account will have one usernae and one pass
PASS_FILE = 'password.json'
def get_pass_json_data():
if os.path.isfile(PASS_FILE):
with open(PASS_FILE) as fp:
return json.load(fp)
return {}
def get_pass():
account = input("What account is this for?")
data = get_pass_json_data()
if account not in data:
print('You do not have this account in the saved data!')
else:
print(data[account])
def savingPasswords():
username = input("Enter username")
password = input ("Enter password")
account = input("What account is this for?")
data = get_pass_json_data()
# this will update your pass and username for an account
# if already exists
data.update({
account: {
'username': username,
'password': password
}
})
with open(PASS_FILE, 'w') as fp:
json.dump(data, fp)
print ("Login successfully saved!")
actions = {
'add': savingPasswords,
'get': get_pass
}
def display():
print("Do you want to add a password to get a password? get/add")
action = input()
try:
actions[action]()
except KeyError:
print('Bad choice, should be "get" or "add"')
while True:
display()
The problem was with your second function. I would advise using with open to open and write to files since it looks cleaner and it is easier to read. In your code you never wrote to the file or closed the file. The with open method closes the file for you after the indented block is executed. I would also recommend writing to something like a csv file for organized information like this so it will be easier to retrieve later.
def display():
response = input("Do you want to add a password to get a password? (get/add)\n")
if response.upper() == "GET":
get_password()
elif response.upper() == "ADD":
write_password()
else:
print("Command not recognized.")
exit()
def write_password():
with open("password.csv", "a") as f:
username = input("Enter username: ")
password = input("Enter password: ")
account = input("What account is this for? ")
f.write(f"{username},{password},{account}\n") # separates values into csv format so you can more easily retrieve values
print("Login successfully saved!")
def get_password():
with open("password.csv", "r") as f:
username = input("What is your username? ")
lines = f.readlines()
for line in lines:
if line.startswith(username):
data = line.strip().split(",")
print(f"Your password: {data[1]}\nYour Account type: {data[2]}")
while True:
display()
Write to a file:
password="my_secret_pass"
with open("password.txt","w") as f:
f.write(password)
to read the password from the file, try:
with open("password.txt","r") as f:
password = f.read()
You can use Pickle: a default python package to save data on file
use:
######################
#py3
import pickle
#py2
import cpickle
#################
file = "saves/save1.pickle"
#you can specify a path, you can put another extension to the file but is best to put .pickle to now what is each file
data = {"password":1234, "user":"test"}
#can be any python object :string/list/int/dict/class instance...
#saving data
with open(file,"w", encoding="utf-8") as file:
pickle.dump(data, file)
#retriveing data
with open(file,"r", encoding="utf-8") as file:
data = pickle.load(file)
print(data)
#-->{"password":1234, "user":"test"}
print(data["password"])
#-->1234
it will save the data you put in "data" in the file you specify in "file"
more info about pickle

Why the context of the file cannot read from the txt file?

I have creat a new empty txt file, but the code below read and write it.
f = open('users.txt', 'r+')
users = eval(f.read()) #f.read()read a string,eval()transfer string to dict
for i in range(4):
name = input('Input Username: ')
passwd = input('Input password: ')
c_passwd = input('Confirm password again: ')
if len(name.strip()) != 0 and name not in users and len(passwd.strip()) != 0 and passwd == c_passwd:
users[name]= {'passwd':passwd, 'role':1} #insert new data, role 1: Customer; role 2: Restaurant; role 3: Admin
f.seek(0)
f.truncate() #clear file
f.writelines(str(users)) #write data to file from dict
print('Congratulations, Register Success. ')
f.close()
break
elif len(name.strip()) == 0:
print('Username could not be empty. Remain %d chance' %(3-i))
elif name in users:
print('Username repeat. Remain %d chance' %(3-i))
elif len(passwd.strip()) == 0:
print('Password could not be empty. Remain %d chance' %(3-i))
elif c_passwd != passwd:
print('Password not same. Remain %d chance' %(3-i))
#log in
f = open('users.txt', 'r', encoding='utf8')
users = eval(f.read())
for count in range(3):
name = input('Input Username: ')
password = input('Input password: ')
if name in users and password == users[name]['passwd']:
print('Log in successful!')
break
else:
print('Username or/and Password is/are wrong,You still have %d chance'%(2-count))
f.close()
The System showed
Traceback (most recent call last):
File "C:/Users/zskjames/PycharmProjects/Fit5136/Register, log in.py", line 4, in <module>
users = eval(f.read()) #f.read()read a string,eval()transfer string to dict
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Do anybody could tell me how to fix that? And how to avoid this mistakes in the future.
You probably want your text file to contain JSON, in order to easily interact with it and turn it into a dict.
In order to do that, you would need to replace your eval with a json.load:
import json
with open('users.txt', 'r+') as f:
users = json.load(f)
# rest of your code
In order for it to work, your text file should look something like the following:
{"John Doe": {"passwd": "somepass", "role": 1}}
In addition, you need to replace:
f.writelines(str(users)) #write data to file from dict
to:
json.dump(users, f)

how to fix python login script using txt files to login and register users

I wrote a python script for logging people in and registering. it used a txt file to store the usernames and passwords. I wrote it in http://trinket.io. However, It does not work in regular python. can anyone tell me what i need to change to fix it?
edit:
here is the code
file = open('accounts.txt', 'a+')
lines = file.readlines()
login = {}
for line in lines:
key, value = line.strip().split(', ')
login[key] = value
while True:
command = input('$ ')
command_list = command.split(' ')
if command_list[0] == 'login':
username = command_list[1]
password = command_list[2]
try:
if login[username] == password:
print('login')
else:
print('no login')
except KeyError:
print('no login')
elif command_list[0] == "register":
file.write("\n")
file.write(command_list[1])
file.write(", ")
file.write(command_list[2])
elif command_list[0] == "help":
print("""To login, type login, then type the username and then type the password.
To register, type register, then type the username and then the password.""")
elif command_list[0]== "quit":
break
else:
print('unrecognised command')
The following edits, marked by ##### ADDED LINE should solve your issue.
Explanations:
(1) You need to use .seek() before you read from a file that was opened in a+ mode.
(2) Using .flush() will force whatever data is in the buffer to be written to file immediately.
(3) Without me restructuring your program too much, this edit allows you to immediately access the newly registered user to login with. This is because, as the program is structured now, you only add details to your login dictionary when you first open the accounts file.
file = open('stack.txt', 'a+')
file.seek(1) ##### ADDED LINE (1)
lines = file.readlines()
login = {}
for line in lines:
key, value = line.strip().split(', ')
login[key] = value
...
elif command_list[0] == "register":
file.write("\n")
file.write(command_list[1])
file.write(", ")
file.write(command_list[2])
file.flush() ##### ADDED LINE (2)
login[command_list[1]] = command_list[2] ##### ADDED LINE (3)
Hope this helps!

Python login script using dictionary

I am making a login script for python and it will create passwords and write them to a text file like (username:password). But I want to add a login script that will check to see if the username and password is in the text file.
def reg():
print('Creating new text file')
name = input('Username: ')
passwrd = input('Password: ')
with open("users.txt", "r+") as f:
old = f.read()
f.seek(0)
f.write(name + ":" + passwrd + "\n" + old)
f.close()
def login():
user = input("username: ")
passwrd = input("password: ")
with open('users.txt') as f:
credentials = [x.strip().split(':') for x in f.readlines()]
for user,passwrd in credentials:
(This is where i want to add the code)
reg()
login()
I think it would be something like.
for user,passwrd in credentials:
print("found")
else:
print("not found")
If you make credentials a dict, then you can do:
if user in credentials and credentials[user] == password:
//success
else:
//failure
This should work for making credentials be a dict
with open('users.txt') as f:
credentials = dict([x.strip().split(':') for x in f.readlines()])
You just check to see if they match. Note that you need to make the variable names different:
for user2,passwrd2 in credentials:
if (user == user2 and passwrd == passwrd2):
print ("Passed")

Categories

Resources