How can I permanently store user inputs automatically into the dictionary - python

users = {
"Hi":"HM123",
"alan": "12122",
"12": "11"
}
def adder():
new_user = input("Please enter user's name: ").strip()
new_pwd = ""
confirmer = "0"
while new_pwd != confirmer:
new_pwd = input("please enter a new Password: ").strip()
confirmer = input("please confirm your password: ").strip()
if new_pwd != confirmer:
print("passwords does not match!!")
users[new_user] = new_pwd
adder()
I used The dictionary as a collection of usernames and passwords to practice creating a simple functional login page.(i'm importing this as a module to my main file). and when I add new users and passwords this code above temporarily adds it to the dictionary but when I re-run the script and try the new user names and pwds it returns incorect username and password, bc they are not in the dictionary.
was hoping to find a way to add the new usernames and paswwords into the dictionary permanently just with user inputs without having to modify the dictionary my self.

Your dictionary (more or less) is stored in RAM which is voilatile - you cannot (or at least, you shouldn't try to) preserve it between different scripts run.
Thas is why people use databases - they are stored on disk and don't vanish unless something really bad happens ;)
The easiest what would suits your needs is to store them in a single json file. It is a format very similar to python dictionary. Python has json library that allows it to parse such file into pythons dict and the opposite - put the dict back into the file.
Here is the example:
import json
with open("users.json", "r+") as f:
# convert content of file users.json into users variable - it will be a dict
users = json.load(f)
def store_to_file(users):
with open("users.json", "w") as f:
# save the users dict into the file users.json in json format
json.dump(users, f, indent=4)
def adder():
...
store_to_file(users)
adder()
Do not forget to create the file users.json!
{
"Hi": "HM123",
"alan": "12122",
"12": "11"
}

Python dictionaries can be converted to JSON text and written to permanent storage as such.
You could also consider serialisation of the dictionary using the pickle module.
Here's an example of both techniques:
import pickle
import json
PFILE = '/Volumes/G-Drive/users.pkl'
JFILE = '/Volumes/G-Drive/users.json'
users = {
"Hi": "HM123",
"alan": "12122",
"12": "11"
}
with open(PFILE, 'wb') as db:
pickle.dump(users, db) # save the dictionary (serialise)
with open(PFILE, 'rb') as db:
_users = pickle.load(db) # retrieve serialised data
print(_users)
with open(JFILE, 'w') as db:
json.dump(users, db) # save as JSON
with open(JFILE) as db:
_users = json.load(db) # retrieve JSON and convert to Python dictionary
print(_users)
Output:
{'Hi': 'HM123', 'alan': '12122', '12': '11'}
{'Hi': 'HM123', 'alan': '12122', '12': '11'}

Related

Read dictonary of a txt in python

I saved some dictionaries in a .txt with:
# The form of store the data is in a dictionary of a dictionary
data = { "DNI": dni, "Nombre": name, "Apellido": surname, "Usuario": username, "ContraseƱa": password}
with open(dbUsers, "a+") as db:
db.write("\n" + str(data))
# Finally the program send a OK message and close the file
db.close()
print("El usuario y sus datos se han introducido correctamente.")
Now I'm trying to get the different lines (one line, one dictionary) of the .txt with:
with open(dbUsers, "r") as db:
for line in db:
But that lines are not a dictionary so I can't get the different values with the keys. My question is: how can I convert the different lines (with a dictionary format) with a dictionary inside in python?
You can use ast.literal_eval to convert the string to a dict.
import ast
with open(dbUsers, "r") as db:
for line in db:
if not line.isspace():
d = ast.literal_eval(line)
print(d)

Python some strings to list

let's assume that program take these variables;
website = "https://stackoverflow.com/questions/"
username = "BestSithInEU"
password = "S0n'X%`2FU`,t!j-"
My aim that, I want to store these datas with another class;
class forExample:
self.header = ["website", "username / email", "password"]
self.data_list = [website, username, password]
### And I'm using this method from csv library
with open("password.csv", "a", encoding="UTF8", newline="") as f:
writer = csv.writer(f)
write multiple rows
writer.writerows(self.data_list)
How can I convert these three variables to list of strings? And also when I use this self.data_list I'm getting this output...
website
username/email
password
h,t,t,p,s,:,/,/,s,t,a,c,k,o,v,e,r,f,l,o,w,.,c,o,m,/,q,u,e,s,t,i,o,n,s,/
B,e,s,t,S,i,t,h,I,n,E,U
_csv.Error: iterable expected, not NoneType
The csv writer expects a list of lists. So
self.data_list = [ [website, username, password] ]

How to add a number to dict value every time i call it?

I want to put a dictionary which contains user information into a new json file and i want it to give every user a number when i call a function 'new_user'. How can i do it?
from get_stars import rate_service
user_info = {
'user_number': int(),
'user_info': {
'username': 'username',
'user_location': 'user_location',
'used_application': 'used_application',
'stars': int()
}
}
def get_user_info():
new_user = user_info.copy()
new_user['user_info']['username'] = input(f"\nEnter your name: ")
new_user['user_info']['stars'] = rate_service()
return new_user
from userinfo import get_user_info
import json
def new_user():
user = get_user_info()
filename = f"user.json"
with open(filename, 'w'):
json.dump(filename, user)
For example i call that func and in my json file there is dict with user number 1, but when i call it next time this number increases by 1
If you want to avoid reading the file before assigning the number I would use a Guuid, that is basically a random number so big that is at all effects guaranteed not to collide with others.
If you want to assign a integer then you have two choices:
reading the files taking the max value and assign before setting
the user info
having another file with the "metadata" of the user
count which you will also read.
Normally this kind of operations are made using a database that will take care out of them.
You can also use a indexed dataframe a numerated dictionary or even a list of user as a middle data-structure that will help you if you go for the option 1.
Assign a uuid: https://docs.python.org/3/library/uuid.html
import uuid
new_user = {}
new_user['user_number'] = uuid.uuid1()
# output: {'user_number': UUID('d2586590-abb8-11ec-94de-acde48001122')}
print(new_user)

How to assign a name to a dictionary based on input from a user

How do we assign a dictionary a name that is taken from input from the user and save that dictionary to a txt file so that we can search for it by its name and print output to the user?
I am currently here:
Any ideas how?
import sys
import pathlib
'''Arg-V's should be in following order <app.py> <action> <nick_name> <name> <phone> <email>'''
if str(sys.argv[1]).lower == 'add':
current = {'Name': sys.argv[3], 'Phone Number': sys.argv[4], 'Email': sys.argv[5]}
with open('contacts.txt', 'w') as f:
f.write(current)
As per Naming Lists Using User Input :
An indirect answer is that, as several other users have told you, you don't want to let the user choose your variable names, you want to be using a dictionary of lists, so that you have all the lists that users have created together in one place.
import json
name = input('name/s of dictionary/ies : ')
names = {}
name = name.split()
print(name)
for i in name:
names[i]={}
print(names)
for i in names:
print(i,'--------->', names[i])
for i in names:
names[i] = '1'*len(i)
for i in names:
with open(i+'.txt', 'w+') as file:
file.write('prova : '+json.dumps(names[i]))

How do I add a variable to a JSON list in Python?

I have a JSON file that looks likes this:
{ "users":"John, admin"}
What I want is to be able to add a string into the "users" title.
So, basically, I want to allow users to input a new username and add it to this list. Take the following Python code:
newUserInfo = input("Enter a new username: ")
And then say I input "Michael"
Then the JSON file should look like this:
{ "users":"John, admin, Michael"}
I've tried the following:
with open(userFile, "a") as userobj:
newUserInfo = json.dump(allUserInfo["users": newUserInfo], userobj)
And It returns an error. Is there an easy way to do this?
Thanks in advance.
Append the name to the string:
import json
s = '''{"users":"John, admin"}'''
data = json.loads(s)
newUserInfo = input("Enter a new username: ")
data['users'] += ', ' + newUserInfo
s2 = json.dumps(data)
print(s2)
Output:
{"users": "John, admin, Michael"}
But a more natural way to use JSON would be represent the names in a list:
import json
s = '''{"users":["John","admin"]}'''
data = json.loads(s)
newUserInfo = input("Enter a new username: ")
data['users'].append(newUserInfo)
s2 = json.dumps(data)
print(s2)
Output:
{"users": ["John", "admin", "Michael"]}

Categories

Resources