How can I fix python printing unnecessary "in range" information - python

I want to make a advanced password generator. And I want to add a feature where each password is saved in a text file. But at the last part where it generates another password, Python prints each character step by step this causes to save each character! My computer crashed 3 times today because of this bug. Sorry for all the bad grammar or bad explanation.
Anyways here is my code:
import random
Alphabet = "abcdefghilmnopqrstuvwxyzABCDEFGHILMNOPQRSTUVWXYZ123456789()]\%$*#!><?"
FileAlphabet = "abcdefghilmnopqrstuvwxyz"
number = input("Number of passwords? ")
number = int(number)
length = input("Password length? ")
length = int(length)
for p in range(number):
password = ''
for c in range(length):
password += random.choice(Alphabet)
print(password)
text = password
saveFile = open("MOST_RECENT_PASSWORD.txt", 'w')
saveFile.write(text)
saveFile.close()
new = input("Generate another password? yes/no" )
FileName = ''
if new == "yes":
for pwd in range(number):
password = ''
for c in range(length):
password += random.choice(Alphabet)
FileName += random.choice(FileAlphabet)
password += random.choice(Alphabet)
print(password)
saveFile = open(FileName + ".txt", 'w')
saveFile.write(text)
saveFile.close()

Your last 2 for loops.
especially the
for c in range(length):
password += random.choice(Alphabet)
FileName += random.choice(FileAlphabet)
password += random.choice(Alphabet)
print(password)
saveFile = open(FileName + ".txt", 'w')
saveFile.write(text)
saveFile.close()
you're saying that for every character of your password it should:
increment the password by some random letter
And change the filename to a random letter
then increment the password again with some random letter
//printing the password is kinda ok allthough it only prints 2 characters
and then you save the 2 characters in ONE file
and redo every time
The bold parts are where the problems lie.
You have to move FileName += random.choice(FileAlphabet)
to the left, so under for c in range(length):
then also move
saveFile = open(FileName + ".txt", 'w')
saveFile.write(text)
saveFile.close()
to the left so it doesn't loop it.
For you the solution should be
for pwd in range(number):
password = ''
for c in range(length):
password += random.choice(Alphabet)
password += random.choice(Alphabet)
print(password)
FileName += random.choice(FileAlphabet)
saveFile = open(FileName + ".txt", 'w')
saveFile.write(text)
saveFile.close(
)

Related

why closes my python program without fully executing?

I am completely new to programming and started a few days ago with learning Python(v.3.8.8). I wanted to make a small password manager, but with a little secret function(I think that's not important and it would take too much time to describe). Anyways I converted the main.py to a .exe with auto-py-to-exe but every time I wanna execute the .exe I can only enter my Login data and the window instantly closes but in Pycharm everything works totally fine. Does anyone know why?
EDIT: It works now, there was no missing "Input()" or stuff like that, I had a spelling mistake in my code and pycharm ignored it!
from cryptography.fernet import Fernet
welcome = input("Login(1), New User (2): ")
def new_user(): # creates a new user and safe the Username and pw in a .txt
print("The login is just for the safety of your data, everything is stored on your local PC!")
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
key = Fernet.generate_key()
f = Fernet(key)
f.encypt(b'password')
file = open(username + ".txt", "w")
file.write(username + ":" + password)
#file.close()
login() # go to login after everything is safed in the .txt
else:
print("Passwords do NOT match!")
def login(): # checks if the entered username and pw match with the .txt content
login1 = input("Login:")
login2 = input("Password:")
file = open(login1 + ".txt", "r")
pw = file.readline()
#file.close()
if pw == login1 + ":" + login2: # infinte trys to enter the username and pw
print("Welcome " + login1)
pwrequest()
else: # returns to login() if the pw is incorrect
print("Incorrect username or password. Please try again")
login()
def pwrequest():
q = input("safe new Password(1), show safed passwords(2)")
if q == "2":
data() # show all saved pw
if q == "1":
newdata() # go to data() if the user want to add a new pw or
# want to acces the hidden part
def data():
file = open('1.txt', 'r') # prints all saved passwords
file_pw = file.read()
print(file_pw)
file.close()
c = input("Press (1) to delete something and press (2) to log out.")
if c == '1':
delete() # delete a pw or acces to hidden part
if c == '2':
login() # simple logout system, probably have to change this to something more intermediate
def newdata(): # safes the data in variables and put it in a .txt file
company = input("Enter the companys name: ")
username = input("Enter your username: ")
password = input("Enter your password: ")
print(company + username + password + ", is everything correct?")
a = input("y/n")
if a == "y":
file = open("1.txt", "w")
file.write(
"Company: " + company + "\n" + "Username: " + username + "\n" + "Password: " + password + "\n" + "\n")
file.close()
pwrequest() # return to pwrequest()
if a == "n":
newdata() # return to newdata() if something is incorrect
secretWord = "CompanyUsernamePassword" # define the secret word to finaly acces the hidden part
if company + username + password == secretWord:
secrettest() # go to secrettest() to enter the secret word
def delete(): # just simple code that delete specific content of the pw .txt
name = input("Please enter the Company, Username and password you wanna delete: ")
with open("1.txt", "r") as f:
lines = f.readlines()
with open("1.txt", "w") as f:
for line in lines:
if line.strip("\n") != name:
f.write(line)
def secrettest():
key = Fernet.generate_key()
f = Fernet(key)
truepass = f.encrypt(b"Test1234")
trys = 3
while trys != 0: # checks if you entered the correct pw and if not count 2 times
password = input("Pls enter the password: ")
d = f.decrypt(truepass)
if password == d.decode():
print(truepass)
break
else:
print("Wrong password!")
trys -= 1
if trys == 0:
print("You entered the wrong password to many times!")
if welcome == "1": # should probably try to move that to the top
login()
if welcome == "2": # this too
new_user()
I think I know why the .exe always closes. I executed the .exe in the windows cmd, and got this error "AttributeError: 'Fernet' object has no attribute 'enrcypt'". I'm kinda sure that this is the part that caused the trouble. I'm just wondering why pycharm just ignored this error...

Password generator generates the same passwords

I'm trying to make a password generator in Python but I have some problems with it.
My code is down below:
import random
import time
f = open("password_list.txt", "a+")
start = time.time()
password = ""
chars= "123456789"
number = int(input("Number of passwords to generate? = "))
length = int(input("Password length? = "))
for p in range(number):
password = ""
for c in range(length):
password += random.choice(chars)
print(password)
f.write(password + "\n")
print('time: ' + str((time.time() - start)) + ' sec')
f.close()
Everything works fine but the only problem is sometimes it generates the same passwords in the text file. How can I avoid that?
One way to avoid the duplication issue is to put the passwords into a set in your loop, and keep looping until the length of the set is the number of passwords you want to generate. Then you can write the contents of the set to the file. This shows how to generate the set of passwords:
import random
chars= "123456789"
number = 5
length = 8
passwords = set()
while len(passwords) < number:
password = ""
for c in range(length):
password += random.choice(chars)
passwords.add(password)
print(passwords)
Sample output:
{'67824479', '67159221', '78423732', '77922952', '83499619'}

Python password system with lock after certain number of attempts

So I am trying to create a password system in Python, whereby after a certain number of incorrect attempts, the user will be blocked from accessing it for, say, 5 minutes. I am currently unsure how the values of the variables can be kept after rerunning the same file and then used in this manner. Could someone help me with this, as I am currently still new to Python?
Update:
After experimenting for a while with the code Jonas Wolff provided me I finalised my code to the following:
def password():
count = 0
currentTime = float(time.time())
passwordList = ["something", "password", "qwerty", "m42?Cd", "no"]
passwordNum = random.randint(0, 4)
password = passwordList[passwordNum]
with open("password.txt", "r") as file:
check = file.readline()
initialTime = file.readline()
if initialTime=="":
initialTime==0
if int(check)==1 and (currentTime-float(initialTime))<300:
print("You are still locked")
print("Please try again in", int(300-(currentTime-float(initialTime))), "seconds.")
quit()
print("The randomised password is No.", passwordNum+1) #Prints a string to let the user know which password was randomly selected
while count<5:
inp = input("Enter the Password: ")
if inp==password:
print("Access Granted")
print()
f = open("password.txt", "w")
f.write("0\n0")
f.close()
select()
elif (count+1)==5:
print("You have been locked")
print("Please try again in 5 minutes")
f = open("password.txt", "w")
f.write("1\n")
f.write(str(currentTime))
f.close()
quit()
else:
count+=1
print("Incorrect Password")
print("You have", 5-count, "tries left.")
continue
Thanks a lot for the help you have provided and the patience with which you answered my questions.
import YourProgram # this is the program you want to run, if the program runs automaticly when opened then move the import to the part where i wrote YourProgram() and delete the YourPregram() line
import time
pswd = "something"
count = 0
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
numa = file_info.count("1")
count = numa
while True:
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
tima = file.readline()
inp = input("What is the password:")
if inp == pswd:
if tima == "":
tima = "0" # this should solve yoúr problem with float convertion however it doesn't make sence that this step should be needed
if str(file_info[:5]) != "11111" or time.time() > float(tima):
YourProgram() # this is just meant as the thing you want to do when when granted acces i magined you where blocking acces to a program.
f = open("PhysxInit.txt", "w")
f.write("\n")
f.close()
break
else:
count += 1
f = open("PhysxInit.txt", "w")
f.write(("1"*count)+"\n"+str(tima))
if count == 5:
f.write(str(time.time()+60*5))
f.close()
#f = open("PhysxInit.txt", "w")
#f.write("\n")
#f.close()
does this work?
just make sure you have a text file called PhysxInit.txt
after running the program, and having guessed wrong a few times my txt file look like this.
11111
1536328469.9134998
it should look something like mine though the numbers may be diffrent.
To read a specific line as you requested you need to do:
with open("PhysxInit.txt", "r") as f:
for w,i in enumerate(f):
if w == #the number line you want:
# i is now the the line you want, this saves memory space if you open a big file

python sava data into txt file

I have problem to create a full coding python file handling. I need all data functions in python will be save in txt file. Below is my coding.
def getListFromFile(fileName):
infile = open(fileName,'r')
desiredList = [line.rstrip() for line in infile]
infile.close()
return desiredList
def main():
staffRegistration()
staffLogin()
regList = getListFromFile("registration.txt")
createSortedFile(regList, "afterreg.out")
loginList = getListFromFile("login.txt")
createSortedFile(userLogin, "afterlogin.out")
checkFileRegistration()
checkFileLogin()
def checkFileRegistration():
print("\nPlease check afterreg.out file")
def checkFileLogin():
print("\nPlease check afterlogin.out file")
def staffRegistration():
regList = []
name = input("Name: ")
s = int(input("Staff ID (e.g 1111): "))
regList.append(s)
s = int(input("Staff IC (without '-'): "))
regList.append(s)
s = int(input("Department - 11:IT Dept 12:ACC/HR Dept 13:HOD 41:Top
Management (e.g 1/2/3/4): "))
regList.append(s)
s = int(input("Set username (e.g 1111): "))
regList.append(s)
s = int(input("Set Password (e.g 123456): "))
regList.append(s)
f = open("registration.txt",'w')
f.write(name)
f.write(" ")
for info in regList:
f.write("%li "%info)
f.close
f1 = open("afterreg.out",'w')
f1.writelines("Registration Successful\n\n")
f1.close()
def staffLogin():
serLogin = input("\nProceed to login - 1:Login 2:Cancel (e.g 1/2): ")
if userLogin == "1":
username = input("\nUsername (e.g 1111): ")
l = int(input("Password: "))
if userLogin == "2":
print("\nLogin cancelled")
f = open("login.txt",'w')
f.write(username)
f.write(" ")
for info in userLogin:
f.write("%li "%info)
f.close
f1 = open("afterlogin.out",'w')
f1.writelines("Logged in successful")
f1.close()
def createSortedFile(listName, fileName):
listName.sort()
for i in range(len(listName)):
listName[i] = listName[i] + "\n"
outfile = open(fileName,'a')
outfile.writelines(listName)
outfile.close()
main()
Actually, this program should have five requirements. First is staffRegistration(), staffLogin(), staffAttendance(), staffLeaveApplication(), approval() but I have done for two requirements only and I get stuck at staffLogin(). I need every function will be save in txt file (I mean the data in function).
In line 32 you try to convert a String into Integer. Besides, in your main function, you have an unresolved variable userLogin.
The other problem is in line 43 (staffLogin function), You want to write a long integer but you pass a string. I have tried to fix your code except for userLogin in main.
def getListFromFile(fileName):
infile = open(fileName,'r')
desiredList = [line.rstrip() for line in infile]
infile.close()
return desiredList
def main():
staffRegistration()
staffLogin()
regList = getListFromFile("registration.txt")
createSortedFile(regList, "afterreg.out")
loginList = getListFromFile("login.txt")
createSortedFile(userLogin, "afterlogin.out")
checkFileRegistration()
checkFileLogin()
def checkFileRegistration():
print("\nPlease check afterreg.out file")
def checkFileLogin():
print("\nPlease check afterlogin.out file")
def staffRegistration():
regList = []
name = input("Name: ")
s = int(input("Staff ID (e.g 1111): "))
regList.append(s)
s = int(input("Staff IC (without '-'): "))
regList.append(s)
s = input("Department - 11:IT Dept 12:ACC/HR Dept 13:HOD 41:Top Management (e.g 1/2/3/4): ")
regList.append(s)
s = int(input("Set username (e.g 1111): "))
regList.append(s)
s = int(input("Set Password (e.g 123456): "))
regList.append(s)
f = open("registration.txt",'w')
f.write(name)
f.write(" ")
for info in regList:
f.write("%li "%info)
f.close
f1 = open("afterreg.out",'w')
f1.writelines("Registration Successful\n\n")
f1.close()
def staffLogin():
userLogin = input("\nProceed to login - 1:Login 2:Cancel (e.g 1/2): ")
if userLogin == "1":
username = input("\nUsername (e.g 1111): ")
l = int(input("Password: "))
if userLogin == "2":
print("\nLogin cancelled")
f = open("login.txt",'w')
f.write(username)
f.write(" ")
for info in userLogin:
f.write("%s "%info)
f.close
f1 = open("afterlogin.out",'w')
f1.writelines("Logged in successful")
f1.close()
def createSortedFile(listName, fileName):
listName.sort()
for i in range(len(listName)):
listName[i] = listName[i] + "\n"
outfile = open(fileName,'a')
outfile.writelines(listName)
outfile.close()
main()
There are a lot of problems in the staffLogin() function. e.g. the result of the first input()is bound to serLogin, but this should be userLogin.
If that is corrected, a password is read from the user, but nothing is ever done with it. Should the password be treated as an integer?
Also, if the user enters 2 at first prompt, the code will not set username but it will still try to write username to the file. That will raise a NameError exception.
Finally, the code attempts to write the characters in userLogin to the file as though they are integers. Not only will that not work, it doesn't make sense. Perhaps this should be writing the password to the file?

Read only lines and not the entire thing in python 2.7

How to I make it so in the code below when you register a username and password it it adds a new line to the txt files and when you login it checks every line in the txt files sepretly
and declaring it as correct if any of the lines match the login instead of it checking if the username and password matches the whole thing
print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for
register: ")
if option == "R":
print "Warning Only 1 user can be registered"
usernamer = raw_input("Desired Username: ")
passwordr = raw_input("Desired Password: ")
file = open("Username.txt","w")
file.write(usernamer + '\n')
file.close()
file = open("Password.txt","w")
file.write(passwordr + '\n')
file.close
print "Registered"
else:
usr = raw_input("Username: ")
pss = raw_input("Password: ")
file = open("Username.txt","r")
if usr == file.read():
print "Username correct"
file.close()
else:
print "Username incorrect or not registered"
file.close()
file = open("Password.txt","r")
if pss == file.read():
print "Password correct"
file.close()
else:
print "Password incorrect or not registered"
file.close()
Here is how to find whether a string exists in some line of a file:
contain = False # Indicator of whether some line of a file contains the string
with open(FILENAME, 'r') as file: # Use `with` statement to automatically close file object
for line in file:
if string in line:
contain = True
break
I have modified your code to validate password and username with a password check logic. This should work.
print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for register: ")
if option == "R":
print "Warning Only 1 user can be registered"
usernamer = raw_input("Desired Username: ")
passwordr = raw_input("Desired Password: ")
file = open("Username.txt","a")
file.write(usernamer + '\n')
file.close()
file = open("Password.txt","a")
file.write(passwordr + '\n')
file.close
print "Registered"
else:
usr = raw_input("Username: ")
pss = raw_input("Password: ")
file = open("Username.txt","r")
count = 0
userfound = False
try:
for user in file.readlines():
count += 1
if usr == user.strip():
userfound = True
file.close()
if not userfound:
raise
file = open("Password.txt","r")
passcount = 0
for passcode in file.readlines():
passcount += 1
if count == passcount:
if pss == passcode.strip():
print 'successfully logged in'
else:
print "Password incorrect or not registered"
break
file.close()
except Exception as e:
print 'User login error !!!'
If you just want to check if the user is in the file contents,
if usr in file.read():
do_somethin
"==" checks if the value are same as it is, "in" keyword checks if the substring is in the huge string. In file.read() will have the whole contents as a string.

Categories

Resources