How do I load the username from a csv file? - python

I learned about creating files using python in computer science at school. I have created a piece of code where you can create a username and password and then it saves to a csv file. There is also another option where you can log in. It asks you to enter the username and if it is wrong it says "Username not found". Whatever I enter (even though it is correct) it says Username not found.
This is the main part of the code:
Log = input("Enter Choice here: ")
if Log == "Log In" or Log == "log in" or Log == "Log in" or Log == "log In":
Data = open("F:\\'Filename'.csv", "r")
SavedUser = Data.readline()
Username = input("Username: ")
if Username == SavedUser:
print("Welcome", Username, "!")
Password = input("Password: ")
if Password == Data.readline():
print("It works")
Thank you for all your help.

Your CSV file is probably not being read correctly. Python has a csv library to parse CSV files correctly. What you can do is read the CSV file to a dictionary and then compare username and password.
import csv
action = input("Enter Choice here: ")
if action.lower() == "Log In".lower(): #Convert both strings two lowercase and then compare
reader = csv.reader(open('demo.csv', 'r')) #parsing the csv file correctly
user_dict = dict(reader) #converting iterable reader directly to a dictionary
#{'abc': 'abc123', 'username': 'password'}
username_input = input("Username:")
if username_input in user_dict: #check if username exists as a key in the dictionary
print("Welcome", username_input, "!")
password_input = input("Password: ")
if password_input == user_dict[username_input]:
print("It works")

Related

How to check the username in text file or not and then ask for the password?

loginUsername = input("Enter Username: ")
loginPassword = input("Enter PASSWORD: ")
data=open('database.txt', 'r')
accounts = data.readlines()
for line in data:
accounts = line.split(",")
if (loginUsername == accounts[0] and loginPassword == accounts[1]):
print("LOGGED IN")
else:
print("Login FAILED")
print(accounts)
I want to make a text login system, which will ask for the username first. After checking the text file which stored username and password, the system will ask for password. But I don't know how to read the first column (which is username, the structure of the text file is "username, password"). If i use readlines() and split(","). But there is "n" at the end of the password.
# You should always use CamelCase for class names and snake_case
# for everything else in Python as recommended in PEP8.
username = input("Enter Username: ")
password = input("Enter Password: ")
# You can use a list to store the database's credentials.
credentials = []
# You can use context manager that will automatically
# close the file for you, when you are done with it.
with open("database.txt") as data:
for line in data:
line = line.strip("\n")
credentials.append(line.split(","))
authorized = False
for credential in credentials:
db_username = credential[0]
db_password = credential[1]
if username == db_username and password == db_password:
authorized = True
if authorized:
print("Login Succeeded.")
else:
print("Login Failed.")
The "n" at the end of the password is probably the newline character \n. In order to remove it, you can use the rstrip() function:
mystring = "password\n"
print(mystring.rstrip())
>>> 'password'

Hashed identical strings aren't the same when hashed twice

I have a login program that hashes a string and stores it in a file to create a new account. When I need to log in, the login detail strings get hashed, and the program checks if the hashed strings have a match in the file. The program works without hashing, but when I hash the identical login details, the hash values are not the same. I have checked and the strings are exactly the same. Here is my code:
import tkinter
import math
import os
import hashlib
# The login function #
def login(username, password, file_path):
file_new = open(file_path, "a")
file_new.close()
file = open(file_path, "r")
file_content = file.read()
print(file_content)
file.close()
hashed_username = hashlib.md5(bytes(username, "utf-8"))
hashed_password = hashlib.md5(bytes(password, "utf-8"))
print(f"Hashed username: {hashed_username}, hashed password: {hashed_password}")
if f"{hashed_username},{hashed_password}" in file_content[:]:
return "You were logged in successfully"
else:
return "We could not find your account. Please check your spelling and try again."
# The account creation function #
def newaccount(username, password, file_path):
file_new = open(file_path, "a")
file_new.close()
# Reading the file #
file = open(file_path, "r")
file_content = file.read()
print(file_content)
file.close()
# Hashing the account details #
hashed_username = hashlib.md5(bytes(username, "utf-8"))
hashed_password = hashlib.md5(bytes(password, "utf-8"))
print(f"Hashed username: {hashed_username}, hashed password: {hashed_password}")
file_append = open(file_path, "a")
# Checking to see if the details exist in the file #
if f"{hashed_username},{hashed_password}" in file_content[:]:
file_append.close()
return "You already have an account, and were logged in successfully"
else:
# Writing the hashed details to the file #
file_append.write(f"{hashed_username},{hashed_password}\n")
file_append.close()
return "New account created."
logins_path = "Random Scripts\Login Program\logins.txt"
signin_message = input("Would you like to: \n1. Create an account \nor \n2. Log in\n")
if signin_message == "1":
print("User chose to create account")
newacc_username = input("Input a username: ")
newacc_password = input("Input a password: ")
print(newaccount(newacc_username, newacc_password, logins_path))
elif signin_message == "2":
print("User chose to log in")
username = input("Input your username: ")
password = input("Input your password: ")
print(login(username, password,logins_path))
else:
print("Please enter 1 or 2")
hashed_username = hashlib.md5(bytes(username, "utf-8"))
This function returns a hash object, and when you print it or write it to a file, you get something like this:
<md5 HASH object # 0x7f8274221990>
... which isn't terribly useful.
If you want the actual text of the hashes, call .hexdigest():
hashed_username = hashlib.md5(bytes(username, "utf-8")).hexdigest()
# returns e.g. "47bce5c74f589f4867dbd57e9ca9f808"

Why does my Python program fail to read the second line of my data file?

I am learning python. I wanted to learn to work with text files, so I decided to make a simple console program.
The program does the following:
Asks if you had already a profile.
If no, then asks to create a username and a password. The information is saved in a text file.
If yes, then asks to input your password and username.
When the user doesn't have a profile, everything works well. When the user has a profile and wants to log in, it doesn't work and I don't know why.
The username is saved in the first line of the text file and the password in the second line, so, I use readlines()[0] and readlines()[1].
The username is recognized correctly, but the password doesn't. I get this error
Traceback (most recent call last):
File "Archivo de prueba.py", line 4, in <module>
print(text_file.readlines()[1])
IndexError: list index out of range
This is the code I wrote:
text_file = open("Archivo de prueba.txt", "r+")
def ask_for_account():
global has_account
has_account = input("Do you have an account? (Write \"Yes\" or \"No) ")
ask_for_account()
def create_profile():
create_user = str(input("Type your new username: "))
create_password = str(input("Type your new password: "))
text_file.write(create_user)
text_file.write("\n")
text_file.write(create_password)
def login():
username = text_file.readlines()[0]
password = text_file.readlines()[1]
current_user = input("Type your username: ")
current_password = input("Type your password: ")
if str(current_user) == str(username) and str(current_password) == str(password):
print("Succesfully logged in.")
else:
print("Invalid username or password")
if has_account == "No":
create_profile()
elif has_account == "Yes":
login()
else:
print("Invalid input")
ask_for_account()
text_file.close()
The following code works. I added a few comments to indicate changes.
def ask_for_account():
return input("Do you have an account? (Enter 'Yes' or 'No') ")
def create_profile():
create_user = str(input("Type your new username: "))
create_password = str(input("Type your new password: "))
# Open the file for writing and close it after use.
text_file = open("Archivo de prueba.txt", "w")
text_file.write("{}\n".format(create_user))
text_file.write("{}\n".format(create_password))
text_file.close()
def login():
# Open the file for reading and close it after use.
text_file = open("Archivo de prueba.txt", "r")
lines = text_file.readlines()
text_file.close()
# remove the newline at the end of the input lines.
username = lines[0].rstrip()
password = lines[1].rstrip()
current_user = input("Type your username: ")
current_password = input("Type your password: ")
if current_user == username and current_password == password:
print("Succesfully logged in.")
else:
print("Invalid username or password")
#
# Put program logic in one place after the methods are defined.
#
has_account = ask_for_account()
if has_account == "No":
create_profile()
elif has_account == "Yes":
login()
else:
print("Invalid input")
username = text_file.readlines()[0]
password = text_file.readlines()[1]
The first call to readlines() consumes the entire file and there are no lines remaining for the second call to read, so it returns an empty list.
Read the file once and save the lines in a list, then pick the desired lines from the list:
file_lines = text_file.readlines()
username = file_lines[0]
password = file_lines[1]
Also, be aware that readlines() puts a carriage return \n at the end of every line, so you might have to strip that off depending on how you use these values.

How do I loop my password/username login page and read the password/username from an external file?

I'm aware of the multiple posts and sources regarding how to loop and read from a text file. I'm sorry to be that guy but I'm a recent noob at Python and I'm writing this at 1:00 in the morning.
As the title suggests, how do I loop my login page so that if the user enters details incorrectly then they get another chance to try, until they have entered details correctly. The password/username also needs to be read from an external file.
My code:
print ("\nEnter details to access wallet...\n")
username = 'Janupedia'
password = '12345'
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= £315.37")
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print('\n--------------------------------------------------------\n')
Let's say your text file (credentials.txt) reads:
Janupedia
12345
Maybe something like this will work for you. I've commented the code that I added. You probably want to name the credentials file something else.
print ("\nEnter details to access wallet...\n")
"""
Open File
"""
with open("Credentials.txt", "r") as f:
array = []
for line in f:
array.append(line) #stores username and password
username = array[0]
password = array[1]
login = 0 #initial login status
while login == 0: #as long as login status = 0 loop repeats
userInput = input("Username?")
if username.strip(' \n') == userInput.strip(' \n'):
userInput = input("Password?")
if password.strip(' \n') == userInput.strip(' \n'):
login = 1 #login successful set login status to 1 thus breaking loop
else:
print("Incorrect")
else:
print("Incorrect")
print('\n--------------------------------------------------------\n')
# Login successful loop finished
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= 315.37")
So you want to loop it. Where would a good place for that be? How about when we ask for a question.
Now, look at the condition where we get the right username and password. We don't want to handle it inside the loop. The loop is only there to get the correct username and password.
print("\nEnter details to access wallet...\n")
username = "Janupedia"
password = "12345"
userInput = ""
while userInput != password:
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
break
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print("Welcome!")
print("\n--------------------------------------------------------\n")
print("BTN = 0.10")
print("= £315.37")
todo_list = open("Credentials", "a")
todo_list.write("Username = Janupedia + Password = 12345")
todo_list.close()
print("\n--------------------------------------------------------\n")
Now to read your username/password from a file. Let's make it simple. The first line is the username and the second line is the password. There are no other items.
Now create a proper function.
def read_credentials_from_file(filename):
"""Read the file and return (username, password).
File contents are first line username and second line password.
"""
# Using the `with` statement is current best practice.
with open(filepath, "rt") as user:
username = user.readline().strip()
password = user.readline().strip()
return username, password
Now fix your code to use the function.
username, password = read_credentials_from_file(...)
Note in the function we strip line endings. If you are using Python 3.7, use the breakpoint function to step through the code and watch what it is doing.
do something like this:
password = "password"
username = "username"
theirUsername = input("What is your username")
theirPassword = input("What is your password")
while theirUsername != username or theirPassword != password:
print("incorrect")
theirUsername = input("What is your username")
theirPassword = input("What is your password")
print("correct")
You can read from an external file with file = open("externalfile.txt","r") then do text = file.read() and if the file is formatted as
username
password
do text = text.split("\n") and then username = text[0] and password = text[1]
this is what it should look like with an explanation:
file = open("password.txt","r") #this opens the file and saves it to the variable file
text = file.read() #this reads what is in the file and saves it to the variable text
text = text.split("\n") #this makes the text into a list by splitting it at every enter
username = text[0] #this sets the username variable to the first item in the list (the first line in the file). Note that python starts counting at 0
password = text[1] #this sets the password variable to the second item in the list (the second line in the file)
theirUsername = input("What is your username") #gets username input
theirPassword = input("What is your password") #get password input
while theirUsername != username or theirPassword != password: #repeats the code inside while theirUsername is not equeal to username or theirPassword is not equal to password
print("incorrect") #notifies them of being wrong
theirUsername = input("What is your username") #gets new username input
theirPassword = input("What is your password") #gets new password input
print("correct") #tells them they are corrected after the looping is done and the password and username are correct

Python : Referencing Data from JSON file in python

I'm currently making a username + password login system and have a file containing the usernames and passwords of previously signed up users. The side of the programme that signs up users works perfectly, but I have tried to implement a system to check the data from the file and sign the user in if they input the right data.
Edit: One combination from the database, it's all structured like this; [["ExampleUsername", "BadPasswrdo14130"]]
This is the code:
# Login Interface using files as a 'login database' of sorts?
import json
def autoSave():
with open("Accounts.json", "w") as outfile:
json.dump(accounts, outfile)
def loadUsers():
with open("Accounts.json") as infile:
return json.load(infile)
def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")
for index, item in (accounts):
if item[1] == eUsername and item[2] == ePassword:
print("Logged in")
else:
print("Login failed")
def createUser():
global accounts
nUsername = input("Create Username » ")
nPassword = input("Create Password » ")
entry = [nUsername, nPassword]
accounts.append(entry)
accounts = accounts[:500000]
autoSave()
accounts = loadUsers()
How would I retrieve data from the database file and check that data with the data that the user inputted?
I've tried already but it does not work, always says login failed, which is this bit of the code:
def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")
for index, item in (accounts):
if item[1] == eUsername and item[2] == ePassword:
print("Logged in")
else:
print("Login failed")
In your code accounts is a list. When you're iterating over it, you get sublists. You should iterate over the sublists to get the username and password.
So you can do:
def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")
for item in accounts: #no need for braces
if item[0] == eUsername and item[1] == ePassword:
return "Logged in"
else:
return "Login failed"
print existingUser()
In your current code you seem to have forgotten that in Python list indexes start with 0.
#ForceBru
This is the code I tried to prevent dup accounts, it doesent allow you to dupe accounts but when making a new account, it says its already created when its not, but creates it anyway.
def createUser():
global accounts
nUsername = input("Create Username » ")
nPassword = input("Create Password » ")
for item in accounts:
if item[0] == nUsername:
return "Account Username already exists, try again"
else:
entry = [nUsername, nPassword]
accounts.append(entry)
accounts = accounts[:500000]
autoSave()

Categories

Resources