Python通过简单的文件读写,来实现注册登录

# -*- coding:utf-8 -*-
''''''
username = input('请输入您的姓名:')
password = input('请输入密码:')
with open('get_info.txt','w+',encoding='utf-8') as file:
    file.write('{}\n{}'.format(username,password))
   #file.write('%s\n%s'%(username,password)) 用着行代码就可以不用使用format函数,效果是一样的 print('注册成功!\n开始登录') i = 0 lis = [] while i<3: usn = input('请输入您的姓名:') pwd = input('请输入密码:') with open('get_info.txt','r+',encoding='utf-8') as f: for line in f: lis.append(line) if usn == lis[0].strip() and pwd == lis[1].strip():#strip函数,用于消除空格和换行符 print('登录成功!') break else: print('账号或者密码错误') i+=1



优化修改后

将代码进行优化重写后 文件可以一直存储用户名密码,不再只对第一次输入的用户名密码进行存储,可以对随后的登录,输入上一次的用户名密码,仍然支持登录

# -*- coding:utf-8 -*-

username = input('username:')
password = input('password:')
with open('user1.text','a+',encoding='utf-8') as file:
    file.write('{}\n{}'.format(username,password))#注意format前是加‘.’而不是逗号
    file.write('\n')

i = 0
lis = []


with open('user1.text','r+',encoding='utf-8') as filer:
    for line in filer:
        lis.append(line)
while i<3:
    print('开始登录,请输入用户名,密码:')
    user = input('用户名:')
    pawd = input('密码:')
    for f in range(int(len(lis))):
        if user == lis[f].strip() and pawd == lis[f+1].strip():
            print('登录成功!')
            exit()#退出程序
    else:
        print('用户名或密码错误!')
    i += 1

  

  

posted @ 2019-04-21 19:52  从行动高于承诺到知行合一  阅读(413)  评论(0编辑  收藏  举报