自动生成密码文件

random.choice:随机选择数组里的一个值;

random.sample:随机选择数组里的多个值;选择几个值自己定义数量

random.shuffle:随机打乱取值;

writelines() 方法用于向文件中写入一序列的字符串,比如列表,它会迭代帮你写入文件

老师写的:

import string,random
pwd_len = input('请输入你要产生多少条密码:').strip()
pwds = set() #存放所有的密码
if pwd_len.isdigit():
    pwd_len = int(pwd_len)
    while len(pwds)!=pwd_len:
        num=random.choice(string.digits)
        letter = random.choice(string.ascii_lowercase)
        upper = random.choice(string.ascii_uppercase)
        pun = random.choice(string.punctuation)
        pasd_len = random.randint(6,11) #代表生成密码的长度
        other_len = pasd_len - 4 #剩余的长度
        all_strs = string.digits+string.ascii_letters+string.punctuation
        other_passwd = random.sample(all_strs,other_len)#随机取到剩下的密码
        pwd_list = [num,letter,upper,pun]+other_passwd  #产生密码之后的list
        random.shuffle(pwd_list)#顺序打乱
        pwd_str = ''.join(pwd_list) #最终的密码
        pwds.add(pwd_str+'
')
    else:
        open('passwds.txt','w').writelines(pwds)

else:
    print('条数必须是整数!')

自己写的:

import random,string

pwd_sl=input('请输入要生成的密码个数:')

pwd_set=set()

if pwd_sl.isdigit():
    while len(pwd_set) != int(pwd_sl):
        low_x = string.ascii_lowercase
        upp_d = string.ascii_uppercase
        num = string.digits
        ts = string.punctuation
        mm = low_x + upp_d + num + ts
        rand_pass = ''.join(random.sample(mm, 8))
        pwd_set.add(rand_pass + '
')
    else:
        open('passwds.txt', 'w').writelines(pwd_set)
else:
    print('必须输入整数')
原文地址:https://www.cnblogs.com/ruijie/p/10218777.html