Estou tendo um problema no meu código, eu sei a solução (pelo menos eu acho que sim) mas não sei como resolver. Sou um Dev iniciante ainda e estou com um projeto de fazer um gerador de senhas automático. Porém o erro que estou tendo é que, da primeira vez que eu rodar o código tudo funciona, porém, da segunda em diante os dados que foram armazenados nas listas na primeira vez que o código foi rodado continuam lá, fazendo assim com que a minha segunda senha gerada, tenha a mesma quantidade de caracteres da primeira MAIS os caracteres colocados pelo usuário na segunda vez, fazendo com que a senha fique muito grande e eu não consigo resolver.
Para dar um exemplo, a primeira vez que rodo meu código esse é o Input:
def menu():
print("\n|--------------->PASSWORD GEN V2<---------------|\n"
"| What do you wanna do now? |\n"
"|-----------------------------------------------|\n"
"|1. Search if the site already has a password |\n"
"|2. Create a new password |\n"
"|3. See my passwords |\n"
"|4. Quit |\n"
"|-----------------------------------------------|\n")
time.sleep(1)
Type the number of the choice that you want:
2
How long does your password need to be? Tell me in numbers
4
What site does you want to create this password for?
google
Password Generated!
Output:
Password 1: m4rogoogle
Os 4 primeiros dígitos são aleatórios podendo ser letras maiúsculas e minúsculas, números (de 0 a 9) ou pontuação ( !, @, #, $, % ) e logo após é seguido do site que você deseja criar a senha.
Ao meu ver eu preciso fazer um jeito para que toda vez que a senha for criada, o código escreva no passwordGenV2.txt
e depois faça com que todos os dados da primeira senha sejam excluídos.
Peço desculpas se fiz algo de errado, pois é minha primeira vez usando o site e espero ter sido claro com meu problema.
import os
import random
import time
uppercaseLetter_list = []
lowercaseLetter_list = []
number_list = []
punctuation_list = []
password = []
punctuation = ["!", "@", "#", "$", "%"]
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
path_dir = 'C:/Python/passwordGen/passwordGenV2'
file_name = 'passwordGenV2.txt'
def creating_folder():
if not os.path.exists(path_dir):
os.makedirs(path_dir)
def creating_file():
passwordFile = os.path.join(path_dir, file_name)
if not os.path.exists(path_dir):
open(passwordFile, "w+")
else:
open(passwordFile, "a+")
return passwordFile
def menu():
print("\n|--------------->PASSWORD GEN V2<---------------|\n"
"| What do you wanna do now? |\n"
"|-----------------------------------------------|\n"
"|1. Search if the site already has a password |\n"
"|2. Create a new password |\n"
"|3. See my passwords |\n"
"|4. Quit |\n"
"|-----------------------------------------------|\n")
time.sleep(1)
def creating_pass():
passwordFile = creating_file()
password_lenght = int(input("How long does your password need to be? Tell me in numbers\n"))
password_site = str(input("What site does you want to create this password for?\n"))
password_site = password_site.casefold()
File = open(passwordFile, 'r')
if password_site in File:
print("This site already has a password created!!")
File.close()
else:
File.close()
File = open(passwordFile, 'a+')
for x in range(password_lenght):
picking_random()
password.extend(uppercaseLetter_list)
password.extend(lowercaseLetter_list)
password.extend(number_list)
password.extend(punctuation_list)
random.shuffle(password)
File.write(''.join(map(str, password)))
File.write(password_site)
File.write("\n")
print("Password Generated!")
time.sleep(3)
return password
def picking_random():
ranD = random.randint(0, 3)
if ranD == 0:
currentUppercase_letter = chr(random.randint(65, 90))
uppercaseLetter_list.append(currentUppercase_letter)
if ranD == 1:
currentLowercase_letter = chr(random.randint(97, 122))
lowercaseLetter_list.append(currentLowercase_letter)
if ranD == 2:
currentNumber = random.choice(numbers)
number_list.append(currentNumber)
if ranD == 3:
currentPunctuation = random.choice(punctuation)
punctuation_list.append(currentPunctuation)
return ranD
def main():
creating_folder()
creating_file()
passwordFile = creating_file()
"""print("\nHello, welcome to my Password Generator V2!!!\nIm Zac, your assistant trough this program, i will help you"
" to create the best and most secure passwords there is...\n")
time.sleep(8)
print("First of all, let me show you my Menu, there you can chose the paths that you are going to take :D\n")
time.sleep(7)
print("Loading")
time.sleep(1)
print("Loading.")
time.sleep(1)
print("Loading..")
time.sleep(1)
print("Loading...")"""
time.sleep(2)
while 1:
user_search = ''
menu()
print("Type the number of the choice that you want: ")
user_choice = int(input())
if user_choice == 1:
print("Now, just type in the site that you want to look for: ")
user_search = str(input(user_search))
user_search = user_search.casefold()
print("Okay, lets see if we already have this password here...\n")
time.sleep(3)
File = open(passwordFile, 'r')
buffer = File.read()
File.close()
if user_search in buffer:
print("This site already has a password created!!\n")
time.sleep(3)
else:
print("I don't seem to find any passwords with that site yet... \n"
"Do you wanna create a new password with this site? (type YES or NO)\n")
user_YesorNo = str(input())
user_YesorNo = user_YesorNo.casefold()
if user_YesorNo == 'yes':
creating_pass()
if user_YesorNo == 'no':
print("Okay, then lets go back to the menu!\n")
time.sleep(4)
if user_choice == 2:
creating_pass()
if user_choice == 3:
print("Do you really wanna see your passwords? (This may be unsafe)"
" (type YES or NO)\n")
user_choice2 = str(input())
user_choice2 = user_choice2.casefold()
if user_choice2 == 'yes':
print("Here are all your passwords: \n\n")
File = open(passwordFile, 'r')
count = 0
while True:
count += 1
line = File.readline()
if not line:
break
print("Password {}: {}".format(count, line.strip()))
if 'str' in line:
break
print("\n\n")
time.sleep(4)
else:
break
time.sleep(5)
if user_choice == 4:
print("Good Bye! <3\n")
time.sleep(5)
break
if __name__ == '__main__':
main()