python习题:登录注册小程序(用户名密码存在文件中)、生成随机密码小程序
一、写一个登录注册程序,两个py文件,一个txt文件,用户名和密码存在文件中。
freg = open('users.txt', 'a+', encoding='utf-8')
freg.seek(0)
#定义存放用户名,密码的 字典
users_info = {}
#逐行读取用户名,密码,并存储到字典中
for line in freg.readlines():
users = line.strip().split(',')
users_info[users[0]]=users[1]
# print(users_info)
#注册
while True:
username = input('请输入用户名:').strip()
password = input('请输入密码:').strip()
cpasswd = input('请确认密码:').strip()
if username and password and cpasswd:
if username in users_info.keys():
print('用户名已存在,请重新注册')
continue
else:
if password != cpasswd:
print('两次输入密码不一致,请重新注册!')
continue
else:
freg.write(username+','+password + '\n')
print('%s,注册成功!' % username)
break
else:
print('用户名密码不允许为空')
freg.close()
#登录
freg = open('users.txt','r')
freg.seek(0)
users_info={}
for line in freg.readlines():
users = line.strip().split(',')
users_info[users[0]] = users[1]
freg.close()
for i in range(3):
username = input('请输入用户名:')
password = input('请输入密码:')
if username and password:
if username in users_info:
pwd = users_info[username]
if password != pwd:
print('密码输入错误')
else:
print('%s,欢迎您!'%username)
break
else:
print('用户名不存在!')
else:
print('用户名密码不允许为空!')
else:
print('输入错误次数过多!稍后再试')
二、写一个生成随机密码的程序,随机密码存放在文件中。
#1、输入要生成密码的条数:
#2、生成8位随机密码,密码包括数字,大写字母和小写字母
import random,string
fpwd = open('pwds.txt','a+')
fpwd.seek(0)
counts = input('请输入密码条数:')
for i in range(int(counts)):
num = random.sample(string.digits,2)
sletter = random.sample(string.ascii_lowercase,2)
cletter = random.sample(string.ascii_uppercase,2)
chars = random.sample(string.ascii_letters+string.digits,2)
pwd = num+sletter+cletter+chars
pwds = ''.join(pwd)+'\n'
fpwd.writelines(pwds)