I need to delete all the contents of a list before I finish my loop

Asked

Viewed 35 times

0

I’m having a problem in my code, I know the solution (at least I think so) but I don’t know how to fix it. I am a beginner Dev still and I am with a project to make an automatic password generator. But the mistake I’m having is that the first time I run the code everything works, but from the second onwards the data that was stored in the lists the first time the code was run continues there, thus making my second generated password, has the same amount of characters as the first PLUS the characters placed by the user the second time, making the password too big and I can not solve.

To give you an example, the first time I run my code this is 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

The first 4 digits are random and can be uppercase and lowercase letters, numbers (from 0 to 9) or punctuation ( !, @, #, $, % ) and soon after is followed by the site you want to create the password.

In my view I need to make a way so that every time the password is created, the code writes on passwordGenV2.txt and then have all the data from the first password deleted. I apologize if I did something wrong, because it’s my first time using the site and I hope I’ve been clear with my problem.

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()

1 answer

0

I noticed in your code the unnecessary use of some lists, and also noticed the origin of the error: when using def picking_random there was an increment of these lists that would be the basis to generate the password. the solution would be to clear these lists with [list]. clear() inserted the cleaning of the password list at the beginning of def creating_pass, see how it turned out.

import os
import random
import time


#uppercaseLetter_list = []
#lowercaseLetter_list = []
#number_list = []
#punctuation_list = []
password = []
#numbers = []
punctuation = ["!", "@", "#", "$", "%"]


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():
    password.clear()
    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:
        password.append(chr(random.randint(65, 90)))
    if ranD == 1:
        password.append(chr(random.randint(97, 122)))
    if ranD == 2:
        password.append(random.randint(0,9))
    if ranD == 3:
        password.append(random.choice(punctuation))
    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__':
  • Thanks!! It helped a lot, I’m really new in python programming so I’m kind of lost, but thanks for the answers!

  • I am also starting, I often see other people’s doubts and I end up trying to answer. so I end up learning too!. success in your learning!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.