文件处理案例

# 1、编写文件copy工具
copy_file=input('请输入您的源文件路径:').strip()
inp_file=input('请输入您需复制的文件路径:').strip()
with open(r'{}'.format(copy_file),mode='rt',encoding='utf-8') as f1,\
open(r'{}'.format(inp_file),mode='wt',encoding='utf-8') as f2:
res1=f1.read()
res2=f2.write(res1)
print(res2)

#2、编写登录程序,账号密码来自于文件
inp_name = input('请输入您的用户名:').strip()
inp_pswd = input('请输入您的密码:').strip()
with open('user.txt',mode='rt',encoding='utf-8') as f:
for line in f:
username,password=line.strip().split(':')
if username==inp_name and password==inp_pswd:
print('登陆成功!')
break
else:
print('用户名或密码错误!')

#3、编写注册程序,账号密码来存入文件
inp_name = input('请创建您的用户名:').strip()
inp_pswd = input('请创建您的密码:').strip()
with open('user.txt',mode='at',encoding='utf-8') as f:
f.write('{}:{}\n'.format(inp_name,inp_pswd))

#4、 登录功能代码(附加:可以把之前的循环嵌套,三次输错退出引入过来)
inp_name = input('请输入您的用户名:').strip()
count=1
with open('user.txt',mode='rt',encoding='utf-8') as f:
for line in f:
username,password=line.strip().split(':')
if inp_name==username:
while count <4:
inp_pswd = input('请输入您的密码:').strip()
if password==inp_pswd:
print('登陆成功!')
break
else:
print('密码错误!')
count+=1
else:
print('登录失败')
break
else:
print('用户名不存在,请先注册!')
# 2.1:编写用户登录接口
#1、输入账号密码完成验证,验证通过后输出"登录成功"
#2、可以登录不同的用户
#3、同一账号输错三次锁定,(提示:锁定的用户存入文件中,这样才能保证程序关闭后,该用户仍然被锁定)

inp_name = input('请输入您的用户名:').strip()
count=1
with open('user.txt',mode='rt',encoding='utf-8') as f:
for line in f:
username,password=line.strip().split(':')
if inp_name==username:
with open('close.txt',mode='rt',encoding='utf-8') as f1:
for line1 in f1:
if inp_name==line1.strip():
print('账号:%s已被锁定'%(inp_name))
break
else:
print('账号%s未被锁定,请输入密码'%(inp_name))
while count < 4:
inp_pswd = input('请输入您的密码:')
if password==inp_pswd:
print('登录成功!')
break
else:
print('密码错误!')
count+=1
else:
print('账号锁定')
f2=open('close.txt',mode='at',encoding='utf-8')
f2.write('%s\n'%(inp_name))
f2.close()
break
else:
print('用户不存在,请先注册!')


# 2.2:编写程序实现用户注册后,可以登录,
# 提示:
while True:
msg = """
0 退出
1 登录
2 注册
"""
print(msg)
cmd = input('请输入命令编号>>: ').strip()
if not cmd.isdigit():
print('必须输入命令编号的数字!')
continue
if cmd == '0':
break
elif cmd == '1':
# 登录功能代码(附加:可以把之前的循环嵌套,三次输错退出引入过来)
inp_name = input('请输入您的用户名:').strip()
count = 1
with open('user.txt', mode='rt', encoding='utf-8') as f:
for line in f:
username, password = line.strip().split(':')
if inp_name == username:
while count < 4:
inp_pswd = input('请输入您的密码:').strip()
if password == inp_pswd:
print('登陆成功!')
break
else:
print('密码错误!')
count += 1
else:
print('登录失败')
break
else:
print('用户名不存在,请先注册!')
elif cmd == '2':
# # 注册功能代码
inp_name = input('请创建您的用户名:').strip()
inp_pswd = input('请创建您的密码:').strip()
with open('user.txt',mode='at',encoding='utf-8') as f:
f.write('{}:{}\n'.format(inp_name,inp_pswd))
else:
print('输入的命令不存在')
posted @ 2020-03-16 14:20  多啦a梦与时光机  阅读(143)  评论(0编辑  收藏  举报