I'm trying to get all the passwords that are generated to be saved to a .txt file. The code below is basically what my code looks like because this is the sample code it was based off of.
import random
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456!$%^&*(`)"
while 1:
password_len = int(input("What length would you like your password to be : "))
password_count = int(input("How many passwords would you like : "))
for x in range(0,password_count):
password = ""
for x in range(0,password_len):
password_char = random.choice(chars)
password = password password_char
print("Here is your password : ", password)
This is what I added to have it be saved to a .txt file.
print("\PASSWORDS SUCCESSFULLY GENERATED!\n" "CHECK THE (generated_passwords.txt) FILE WHERE YOUR (PassGen.exe) IS LOCATED TO VIEW THEM!\n")
with open('generated_passwords.txt', 'w') as f:
f.write(password)
But when I run my code it only saves the very last one that was generated and not all of them. How would I fix this? I'm not really sure what to try beyond here because I'm still new to Python so I'm still learning and I haven't seen a solution to my problem anywhere that I've looked.
Im using pyInstaller to turn it into a .exe after the fact as well by the way.
CodePudding user response:
Below code snippet should work for you :)
import random
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456!$%^&*(`)"
while 1:
password_len = int(input("What length would you like your password to be (0 to exit): "))
if password_len == 0: print('Thank you :)'); break
password_count = int(input("How many passwords would you like : "))
with open('./stackoverflow/stack14_generated_passwords.txt', 'a') as f:
for x in range(0,password_count):
password = ""
for x in range(0,password_len):
password_char = random.choice(chars)
password = password password_char
print("Here is your password : ", password)
f.write(password '\n')
print("\nPASSWORDS SUCCESSFULLY GENERATED!\n" "CHECK THE (generated_passwords.txt) FILE WHERE YOUR (PassGen.exe) IS LOCATED TO VIEW THEM!\n")