Random password generator python

151 Views Asked by At

When i run the following code and i open the file called pwd.txt it shows the same password in all the 100 lines

import string
from random import *
characters = string.ascii_letters + string.digits
password =  "".join(choice(characters) for x in range(randint(8,16)))
with open('pwd.txt', 'w') as f:
    for _ in range(100):
        f.write(password + '\n')
1

There are 1 best solutions below

0
On

You only generate one password, outside loop. Generate a new password each iteration instead:

with open('pwd.txt', 'w') as f:
    for _ in range(100):
        password =  "".join(choice(characters) for x in range(randint(8,16)))
        f.write(password + '\n')

Expressions are not automatically re-evaluated when you write them to a file, you need to explicitly run the same expression again and again.

You could put it in a function if you like, but it bears repeating: your password string is not going to be recreated every time you write it to the file without explicitly creating a new string.