I have a whole system created and I just want the users to have to have a username and password to access the system.
This is the code i have written to add the username and password to the saved dictionary, but everytime i run this is just overwrites whatever is in the store.
username=input("What would you like the username to be?")
password=input("What would you like the password to be?")
newperson = {username,password}
pickle.dump(newperson, open("Userstore","wb"))
how would i code it to keep the information already stored in "Userstore" and add the newperson to the dictionary?
You can do the following logic:
check if Userstore present, if it present then read the already saved data.
Code:
import pickle
import os
filename = "Userstore"
userdict = {}
if os.path.isfile(filename):
userdict = pickle.load(open(filename, "rb"))
username = input("What would you like the username to be?")
password = input("What would you like the password to be?")
userdict[username] = password
print userdict
pickle.dump(userdict, open("Userstore", "wb"))
Related
I'm starting my first project (a password manager). What I have done so far is make it so the user can input whether they want to make a new password or look for a password. If they choose to enter a password, the account/purpose for the password and the actual password will be saved to a dictionary. For example, a purpose could be for "yahoo" and the password being "example". That dictionary is then written down in a text file. If the user decides to look for a password, all they would have to do is type in the account for the password. So far everything is working except for the fact that when I enter another password and account, it overwrites the pre-existing password and account instead of adding the new password to the dictionary.
import json
passwords = {
}
prompt = "If you want to make a new password, type 'Make password'."
prompt += "\nIf you want to look for a password, type 'Look for password'.\n"
answer = input(prompt)
def password_list(account_name, password_name):
passwords[account_name] = password_name
answer = answer.upper()
found = 0 # used to see whether account for password can be found
if answer == "MAKE PASSWORD":
account_name = input("What use is this password for? ")
account_name = account_name.upper()
password_name = input("What is the password? ")
password_list(account_name, password_name) # purpose and password saved to dict
with open("passwords.txt", 'w+') as f:
f.write(json.dumps(passwords))
print("Your password was saved!") # dictionary gets saved to text file
elif answer == "LOOK FOR PASSWORD":
with open("passwords.txt", "r") as f:
passwords = json.loads(f.read()) # text file gets opened to read
if not passwords: # if the list is empty...
print("Sorry but there are no passwords available. Make a new one!")
elif passwords: #if the list isn't empty...
search_account = input("What account is this password for? ")
search_account = search_account.upper()
for name in passwords.keys(): # list of accounts get searched
if search_account == name: #if an account is in the dictionary
print(f"The password is '{passwords.get(name)}'.")
found = 1
break
if found != 1:
print("Sorry, we can't find such name.")
Cool project.
It's because every time you start the script you force the password dic to be empty. So when you add a password, it's added to a new empty dic and than you overwrite the file with this empty dic + new_password.
When you code, think about the most likely outcome at every run: the file exists. IF it doesn't, than create it.
This is what I demonstrate here in the load_passwords() function.
As an extra, I propose to you a more Pythonic (and efficient) way to search through a dictionary's keys in O(1) rather than O(n).
import json
prompt = "If you want to make a new password, type 'Make password'."
prompt += "\nIf you want to look for a password, type 'Look for password'.\n"
answer = input(prompt).upper()
def load_passwords():
try:
with open("passwords.txt", "r") as f:
passwords = json.loads(f.read()) # text file gets opened to read
return passwords
except FileNotFoundError:
print("Sorry but there are no passwords available. Make a new one!")
return {}
def password_list(account_name, password_name):
passwords = load_passwords()
passwords[account_name] = password_name
return passwords
if answer == "MAKE PASSWORD":
account_name = input("What use is this password for? ").upper()
password_name = input("What is the password? ")
passwords = password_list(account_name, password_name) # purpose and password saved to dict
with open("passwords.txt", 'w+') as f:
f.write(json.dumps(passwords))
print("Your password was saved!") # dictionary gets saved to text file
elif answer == "LOOK FOR PASSWORD":
passwords = load_passwords()
if passwords: #if the list isn't empty...
search_account = input("What account is this password for? ").upper()
# this is much better
if search_account in passwords:
print(f"The password is '{passwords.get(search_account)}'.")
else:
print("Sorry, we can't find such name.")
Note: Be sure to encrypt your passwords before saving to a file.
"You should probably initialize your password list by reading your json file if it's there. Otherwise, when you run MAKE PASSWORD, it adds the new password to an empty dict and overwrites the existing password file which might've had a password in there before." – rchome
I am creating a registration system, which register the username and password of a person in a dictionary and then passes that dictionary to a .txt file. See the example:
user = 'Lucas'
password = '1234'
dic = {}
dic[user] = password
import pickle
archive = open('data.txt', 'ab')
pickle.dump(dic, archive)
archive.close()
archive = open('data.txt', 'rb')
dic = pickle.load(archive)
archive.close()
print(dic)
The problem is that my program will register infinite users and forever, so if now I put another user and another password it should return a dictionary with all users already registered + the user being registered, the problem is that it is returning a dictionary only with the last registered user. How could I solve it?
i am learning python, and i wanted to create a little login and register program, that writes the username and the password to a txt file (so that it can be later used), i am currently working on the register function, when i try to write to the txt files it does nothing, i tried doing a with loop, a .flush() and .close() but neither of them saves the info.
Here's my code:
username.write = input ('username > ')
password = open("password.txt", "w")
password.write = input ('password > ')
print('Welcome.')
username.close()
password.close()
What am i missing?
Edit.
Neither 3 of the solutions to the suggested question work for me...
Get your input and store them in two variables and then write them to files:
username = input ('username > ')
password = input ('password > ')
with open('usernames.txt', 'w') as userFile:
userFile.write(username)
with open('passwords.txt', 'w') as passFile:
passFile.write(password)
yourfile.open(filename,'w')
username = input()
password = input()
yourfile.write(username)
yourfile.write(password)
yourfile.close()
This question already has answers here:
Saving and loading multiple objects in pickle file?
(8 answers)
Closed 4 years ago.
import pickle
import hashlib
import uuid
def ask_pass():
username = input("Please create your username: ")
password = input("Please create your password: ")
salt = uuid.uuid4().hex
hash_code = hashlib.sha256(salt.encode() + password.encode())
dict = {username: {'SALT': salt,
'HASH': hash_code.hexdigest()
}
}
input_user=open("file.txt", "wb")
pickle.dump(dict, input_user)
I want to add multiple user to the file.txt but my code delete the previous username and password in stored file.txt every time when i create new username and password. what needs to be change in order to have every user information store it in the file.txt, also how existing users can change their password that being created before?
You are overriding the file each time you save it, losing the previous information.
You need to check it exists and, if that's the case, open it, read it and add the new key to it and, if it doesn't exist, create a new one. Check the code below.
Besides, you should be cautious using open (you can use with or close, as stated here).
import os
import pickle
import hashlib
import uuid
def ask_pass():
if os.path.isfile("file.txt"):
with open("file.txt", "rb") as fp:
dict = pickle.load(fp)
else:
dict = {}
username = input("Please create your username: ")
password = input("Please create your password: ")
salt = uuid.uuid4().hex
hash_code = hashlib.sha256(salt.encode() + password.encode())
dict[username] ={'SALT': salt,
'HASH': hash_code.hexdigest()
}
with open("file.txt", "wb") as fp:
pickle.dump(dict, fp)
def info(): #Here you can write your password and username.
Username = raw_input ("Username: ")
Password = raw_input ("Password: ")
print("")
for line in open('/home/hello/Usernames.txt'):
if Username == Username in line: #Checks if username is available.
print ("Username is already taken!\n")
info()
else:
User = open("/home/hello/Usernames.txt", "w") #Registers username.
User.write(Username)
Psw = open("/home/hello/Passwords.txt", "w") #Registers password.
Psw.write(Password)
print ("You have succsesfully registered!") #If you managed to register.
break
info()
This is an account registerer that can register both username and password. But I need help with something... How can I make it check multiple lines of strings in a file, and how can I make the program write a new line of string in the text files when I register without replacing the old string?
Open the file for appending ('a') mode instead of writing ('w') which truncate the file.