Python Random Password Generator

Fri, 20 May 2011

I was playing with Python some more and made a nice little Python Random Password Generator that you can use. You can just copy/paste and hit F5 in IDLE. I'm using Python 2.7, but I don't think it matters in this case.

# Password Generator
# JREAM.com
import string
import random

def rand(x):       
    s = string.lowercase[:26]
    s += string.uppercase[:26]
    s += string.digits
    return ''.join(random.choice(s) for i in range(x))

def save(result):
    fname = 'password.txt'
    file = open(fname, 'a');
    for i in result:
        print >> file, i            
    file.close()
    print 'File saved ('+ fname +')'        

if __name__ == '__main__':
    howMany = raw_input('How many characters do you want your passwords? ')
    howLong = raw_input('How many times? ')
    howMany = int(howMany)
    howLong = int(howLong)
    result = []

    # Builds a list of passwords
    for i in range(howMany):
        result.append(rand(howLong)) # Thanks ledinscak for the type correction :)

    saveQ = raw_input('Do you want to save? y/n: ');
    if saveQ == 'y':
        # Save the list of passwords
        save(result)
    else:
        print 'File not saved'
        
    print result