python作业/练习/实战:生成随机密码

作业要求
1、写一个函数,函数的功能是生成一批密码,存到文件里面
  def gen_password(num):
  #num代表生成多少条密码
2、密码复杂度要求
  1)长度在,8-16位之间
  2)密码必须包括大写字母、小写字母、数字、特殊字符
  3)密码不能重复
3、生成的密码保存到文件里面

方法1提示
1、先分别从大写字母、小写字母、数字、特殊字符中各取一个 4个
2、再从所有的字符里面取4-12个,和第一部获取到的结果拼起来 8-16

import string,random
def gen_password():
    for i in range(num):
        pwd_len=random.randint(8,16)  #总长度
        upper =random.sample(string.ascii_uppercase,1)   # choice只返回一个字符,sample返回一个字符串,所以这里我们使用sample
        lower = random.sample(string.ascii_lowercase,1)  # 在所有小写字母中随机选择一个
        digits = random.sample(string.digits,1)
        punctuation = random.sample(string.punctuation,1)
        other=random.sample(string.ascii_letters+string.digits+string.punctuation,pwd_len-4)  #剩余长度为总长度-4,在所有的字母符号数字中取

        res=upper+lower+digits+punctuation+other  #把上面的拼接在一起
        random.shuffle(res)  # 打乱顺序
        # print(''.join(res))
        return ''.join(res)
#将密码保存到文件中
all_passwords=set()
num=int(input('请输入要产生多少条密码  :').strip())
while len(all_passwords)!=num:   #使用集合长度作为循环次数
    res=gen_password()+'
'
    all_passwords.add(res)
with open('pwd.txt','w',encoding='utf-8') as fw:
    fw.writelines(all_passwords)

方法2提示
所有的里面取8-16位,然后看是否和数字大小写字母特殊符号有交集

import string,random

def gen_password2():
    pwd_len = random.randint(8, 16)  # 总长度
    all_str = string.ascii_letters + string.digits + string.punctuation  # 全部
    res=set(random.sample(all_str,pwd_len)) #在全部里取长度,先换成集合,后面好取交集
    if res & set(string.ascii_lowercase) and  res & set(string.ascii_lowercase) and res & set(string.digits) and res & set(string.punctuation):  # 取交集
        return ''.join(res)  # 交集里都有,说明对啦,可以返回res了
    return gen_password2()
#将密码保存到文件中
all_passwords=set()
num=int(input('请输入要产生多少条密码  :').strip())
while len(all_passwords)!=num:   #使用集合长度作为循环次数
    res=gen_password2()+'
'
    all_passwords.add(res)
with open('pwd.txt','w',encoding='utf-8') as fw:
    fw.writelines(all_passwords)
原文地址:https://www.cnblogs.com/haifeima/p/9714049.html