How to fix dynamic variable assignment conflict in Python - python-3.x

How do I fix the variable assignment in this Python code? So, I have this python code:
with open('save.data') as fp:
save_data = [line.split(' = ') for line in fp.read().splitlines()]
with open('brute.txt') as fp:
brute = fp.read().splitlines()
for username, password in save_data:
if username in brute:
break
else:
print("didn't find the username")
Okay so, a quick explanation; thesave.data is a file that contains variables of Batch-file game (such as username, hp etc...) and brute.txt is a file that contains "random" strings (like what seen in wordlists used for brute-force).
save.data:
username1 = PlayerName
password1 = PlayerPass
hp = 100
As I said before, it's a Batch-file game so, no need to quote strings.
brute.txt:
username
username1
password
password1
health
hp
So, when the Python code is executed, it loads the two files contents and save them into a list and then iterate through the username and password "brute" them until they match with what on brute.txt, and they assign themselves automatically. But, the problem is with the assignment, when i try to print them (the variables) this happens:
## We did all the previous code
...
>>> print(save_data)
[['username', 'PlayerName'], ['password', 'PlayerPass'], ['health', '100']]
>>> print("Your username is: " + username)
username
>> print("Your password is: " + password)
PlayerName
>> print("Your health is: " + hp)
NameError: name 'hp' is not defined
So, any idea on how to fix the assignment conflict? If you didn't understand something, kindly comment it and I will clear it up.

and they assign themselves automatically
This isn't a thing. I suppose you're imagining that the pseudo-variables pseudo-defined in save.data will become Python variables in your program. They won't.
Instead, parse them into a data structure and retrieve the values from the data structure.
For example,
with open('save.data') as fp:
save_data = dict([line.split(' = ') for line in fp.read().splitlines()])
...
print(save_data["hp"])

Related

How do I obtain a string from a list and compare it to another string?

So basically I'm making something fun for myself, and I've run into a problem.
I have a list of illegal items someone can't put into a username string.
Basically, if someone inputs a username, and it contains something in the variable illegal_items, it should not let them input the username.
Problem is, I cannot get it to work properly. Here is what I've tried.
username = "roboticperson"
illegal_items = ['test', 'robotic', 'emphatic']
if any(illegal_items in s for s in username):
print("Your username cannot contain any illegal items.")
else:
print("Hello, "+username+"!")
WHAT IT SHOULD SAY:
Your username cannot contain any illegal items.
WHAT IT SAYS INSTEAD:
TypeError: 'in <string>' requires string as left operand, not list
If this is a duplicate of another thread, my apologies.
EDIT: I'm trying to make it so that anything within the variable illegal_items flags the username as invalid.
for s in username is iterating through the username by character.
Therefore what you are essentially doing is:
is test in r?
is test in o?
do this instead:
username = "roboticperson"
illegal_items = ['test', 'robotic', 'emphatic']
if any( s in username for s in illegal_items):
print("Your username cannot contain any illegal items.")
else:
print("Hello, "+username+"!")
This checks if
is test in roboticperson? //false
is robotic in roboticperson? //true

How do I print back specific data from a list using user input?

In summary I'm trying to create a password manager. The Idea is that the program would ask the user input.
If user writes "new", the program asks input on the website, username and password and then store this data in a text file in the form of a List.
Now the main problem:
I want to be able to access selected data and have the program print said data from the text file to me.
For example:
I input into the program the website "google" along with username: "potato" and password: "potato"
After that, the program asks me what else I want to do. And if I write "access google", I want to program to give me back the website, username and password that are SPECIFIC to the google input.
This is necessary, as I will be adding several different inputs.
I have no idea how to do this and have no tutor. I hope someone can give a solution I can learn from.
Below you will find the base code I have come up with.
Keep in mind that I am a beginner. Thank you.
vault = open("Passvault.txt", "r+")
list = []
action = input("What do you want to do? ")
def tit():
global title
title = input("Add website: ")
return title
def user():
global username
username = input("Create username: ")
return username
def passw():
global password
password = input("Create password: ")
return password
running = True
while running:
creation = True
tit()
user()
passw()
if action == "new":
tit()
user()
passw()
#I added a class here hoping that i could create a class with an argument referencing the title
#so that when i type access "title" in the next if statement it would print back the data
#relevant to the selected title
class new(str(title)):
list.append(tit)
list.append(user)
list.append(passw)
vault.close()
if action == "access" + title:
creation = False
print(title)
print("Username: " + username)
print("Password: " + password)
vault.close()
Here is the code. This code stores the username, password, and website name in the txt file and also prints the username and password w.r.t website name.
import re # used to search patterns.
file_name = 'Passvault.txt'
while True:
action = input("What do you want to do? ")
if action == 'new':
title = input("Add website: ")
username = input("Create username:")
password = input('Create password')
#writing data into the file
with open (file_name,'a') as f:
data = f.write(f'{title} {username} {password}\n')
if 'access' in action:#if input contains access word
website = action.split()[1].strip() #storing website name which is written after access
#reading the data
with open(file_name,'r') as f:
data = f.read()
#searching for all username password related to website
username_pass = re.findall(f'{website}\s+(.*?)\n',data,re.S)#example google sachin 1234
print('Website: ',website)
print('Username, Password',username_pass)
I'm going to give you a more conceptual answer than code, because this is a more long term type of deal.
What you're going to want to do is use json files and dictionaries to store your data so you can search by keys (see the dictionaries link).
Once you've done that you're going to want to wrap everything in a while loop inside a def that gets user input like so:
def get_input():
permitted_actions = ['new', 'access', 'exit']
while True:
action = input("What do you want to do? Valid actions: new, access or type EXIT to end the program.").strip().lower()
if action not in permitted_actions:
print(f"{action} is not a valid action!")
elif action == 'new':
#call another function to do stuff here
elif action == 'access':
#call another function to do stuff here
elif action == 'exit':
print("Shutting down...")
break
I would highly recommend against creating your own actual vault for a password manager until you're much more experienced if you actually intend to use this, otherwise feed it fake passwords and whatnot and learn.
Now when you're adding website data you'll read your dictionary (see the dictionary link) and get the key associated with said website if it exists and then update the info that the user gives.
When you're accessing a website's data you just go to the dictionary (see the dictionary link) and grab the info relating to that website key if it exists.
Remember, you're going to be loading that dictionary from a json file (see the json link).
If you were to make this program an actual program someone would use you'd use a proper database of some sort (python3 has sqlite support natively) and use a database with encryption and master passwords.
I hope this points you in the right direction.
You can save the values as a dictionary with a list as the username and password then use literal_eval to convert the string dict into a dict and access the username and password as well as storing other websites with its own usernames and passwords.
website = 'google'
username,password = 'potato', 'potato'
filename = "yourfilehere"
with open(filename, w) as f:
f.write(str({website: [username,password]}))
#This will save your data as a string dictionary will the data above
#then read the file, get the dictionary and convert it then use its values
from ast import literal_eval
with open(filename, 'r') as f:
data = f.read()
data = literal_eval(data)
#Then search dictionary for website
found = data.get(website)
#Then if it was successful get the username and password
username = found[0]
password = found[1]
As long as you only have the dictionary created as a string in the file you are reading you can use this ethod to save as many website with the allocated username and password saved with it.
You can add a input() into the code to check which site the user wants the username and password for and then search for it in your dictionary.
search = input("Enter the website: ")
try:
found = data.get(search)
#add code here to get username and password
except:
print("failed to find a website matching: %s" % search")

Checking for the password script not working - please check my code for errors

This is my first time using StackOverflow to type a question, can anyone check my code and tell me what seems to be wrong, I wanted to check if the password is written correct or wrong,
when I run that script in the terminal, it displays the "Enter your password" line but when I type in the password, whether it's correct or not, it doesn't do anything and the script ends without displaying any messages from the two messages I put in the if statement, I hope I described the problem well...
password_file = open('SecretPasswordFile.txt')
secret_password = password_file.read()
result = ""
typed_password = input("Enter your Password!: ")
if typed_password == secret_password:
result += "Access granted!"
if typed_password == "12345":
result += "That password is one that an idiot puts on their luggage!!!"
else:
print('Access Denied!!')
print(result)
Here is the solution for the problem i have understood yet
Line if typed_password == "12345": will not work unless user enter correct password
Fix: add it in elif statement
If result is to show desired message like Access Granted or Access Denied!! or That password is one that an idiot puts on their luggage!!!
Fix: Use print() function
Fixed Code
password_file = open('SecretPasswordFile.txt')
secret_password = password_file.read().rstrip() # fix : added rstrip() to trim whitespaces from the right side
typed_password = input("Enter your Password!: ")
if typed_password == secret_password:
print ("Access granted!")
elif typed_password == "12345":
print("That password is one that an idiot puts on their luggage!!!")
else:
print('Access Denied!!')

Matching user input with file data

first of all, I'm new to this site. Hello :)
I have a problem with a program I'm trying to make. What I'm trying to do right now is a login system - so users can enter a username and password (that they've already registered with) and then match the username and password with one in a file called 'accounts.txt'.
This means I can associate data they later generate with their account.
Here's what I have so far:
while loop == (2):
print("Welcome to login.")
verifyuser = input("Enter your username: ")
verifypass = input("Enter your password: ")
f = open("accounts.txt","r")
for line in f:
if re.match(verifyuser, line) and match(verifypass, line):
loop = (3)
Loop 3 takes it along to the rest of the program once it's verified. I know this re.match thing doesn't exactly work, but I have no idea how I could go about this, and I've tried several different routes - I don't mean to ask people to do my work for me or anything, I just can't do this specific area.
Thanks
re.match is for regular expressions, which don't seem to be used here.
https://docs.python.org/2/library/re.html#re.match
While I don't recommend user credentials in files, why aren't you using the equals operator?
if verifyuser == line:
Also, I'm not sure how both verifyuser AND verifypass could be true for the same line?
user_match = False
pswd_match = False
for line in f:
if verifyuser == line:
user_match = True
if verifypass == line:
pswd_match = True
if user_match and pswd_match:
# loop = (3)
I've actually done something just like this, I did it in a different way than you. This is what my text file looked like storing the information:
username : password
Then I would ask for the information like this:
f = open('filename.txt', 'r')
username = input('Enter your username: ')
password = input('Enter your password: ')
user = username + ' : ' + password
if user in f.read():
print('Loggin successful')
else:
print('incorrect username or password')
if you want to give the user like 5 chances you can just add in a nice little for loop.
for i in range(5):
f = open('filename.txt', 'r')
username = input('Enter your username: ')
password = input('Enter your password: ')
user = username + ' : ' + password
if user in f.read():
print('Loggin successful')
break
else:
print('Incorrect username or password')
This isn't the same as my script, mines a bit longer, but this should get the job done!

how to permanently store an input made by a user in python even after the script restarts, the user input will be stored

I am a little stuck with my code I am trying to make a login system where the user can login to their account and use the commands that I have set, but i wanted add some extra input so that the user can register to the login system and use the commands I have set. I wanted to store the input made by the user permanently in a different variable each time so that when the user restarts the peice of code they can log in to the system and they wouldn't need to register again.
Here is the piece of code that I have created so far:
print ("Welcome!")
print ("Would you like to register")
loop = True
while (loop == True):
username = input ("username: ")
password = input ("password: ")
print ("register here if you don't have an account")
username1 = input ("name: ")
print ("this is what you use to login to the system")
username2 = input ("username: ")
username3 = input ("password: ")
if (username == "rohit" and password == "rodude") :
print ("hello and welcome " + username or )
loop = False
loop1 = True
else:
print ("invalid username and password")
while(loop1 == True):
command = str(input(username + "{} > >"))
if(command.lower() == "exit"):
loop1=False
elif(command.lower() == "hi"):
print("Hi " + username + "!")
else:
print ("'" + command + "' is an invalid command!")
Hey guys your ways are too complicated all you could do is this
name = open("usernames.txt", "w") #opens file usernames.txt and gets ready to write to it
file = input("please type some text: ") #asks user for text in code
name.write(file) #writes contents in file to usernames.txt
name.close() #closes file
open1 = open("usernames.txt", "r") #opens file to read it
print (open1.read()) #prints whatever is in the text file
You can't use variables for local storage. If you want information to persist across program runs, you need to store it in a persistent location - typically a disk file or a database. There are a lot of modules available to make this easier, Pickle (as noted in klashxx's response) is an excellent one for simple scenarios.

Resources