python初学者,练习模拟用户注册、登录过程,感觉不够精简,请大神指教!

def write_file(username, passwd):
    with open("user_passwd.txt", mode="a") as fa:
        fa.write("%s: %s\n" %(username,passwd))
def read_file():
    u_dict = {}
    with open("user_passwd.txt", mode="r") as fr:
        for line in fr.readlines():
            line = line.split(":")
            key = line[0].strip()
            value = line[1].strip()
            u_dict.update({key: value})
    return u_dict
# new user registe
def register():
    while True:
        username = input("请输入用户名: ").strip()
        u_dict = read_file()
        if username in u_dict:
            print("用户已存在,请重新输入!")
            continue
        else:
            passwd = input("请设置密码: ")
            write_file(username, passwd)
            print("恭喜您,注册成功!")
            break
# old user login
def login():
    while True:
        username = input("用户名: ").strip()
        passwd = input("密码: ")
        u_dict = read_file()
        # print(u_dict)
        if username not in u_dict or passwd != u_dict[username]:
            print("用户名或密码错误,请重新输入!")
            continue
        else:
            print("登录成功,欢迎您!")
            break

# user interface
def ui():
    while 1:
        prompt = '''(0) register
(1) login
(2) exit
请输入您的选择(0/1/2): '''
        choice = input(prompt)
        cmds = {"0": register, "1": login}
        if choice not in ["0", "1", "2"]:
            print("非法操作,请按要求输入!!!")
            continue
        if choice == "2":
            print("拜拜,欢迎下次光临~")
            break
        cmds[choice]()

if __name__ == '__main__':
    ui()
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 5

使用getpass模块来安全地获取密码,这样密码在输入时不会显示在屏幕上。 对文件操作进行异常处理,以防文件不存在或无法打开。 优化用户输入的处理,减少重复代码。 使用更具描述性的变量名。 将UI与其他逻辑分离,使其更加模块化。

1个月前 评论

import getpass

def write_credentials(username, passwd, filename="user_passwd.txt"):
try:
with open(filename, mode="a") as file:
file.write(f"{username}: {passwd}\n")
except Exception as e:
print(f"Error writing to file: {e}")

def read_credentials(filename="user_passwd.txt"):
credentials = {}
try:
with open(filename, mode="r") as file:
for line in file:
username, passwd = line.strip().split(":", 1)
credentials[username.strip()] = passwd.strip()
except FileNotFoundError:
pass # Ignore if file doesn't exist
except Exception as e:
print(f"Error reading from file: {e}")
return credentials

def register(credentials):
while True:
username = input("请输入用户名:").strip()
if username in credentials:
print("用户已存在,请重新输入!")
else:
passwd = getpass.getpass("请设置密码:") # Password won't be shown on the screen
write_credentials(username, passwd)
print("恭喜您,注册成功!")
break

def login(credentials):
while True:
username = input("用户名:").strip()
passwd = getpass.getpass("密码:") # Password won't be shown on the screen
if username not in credentials or passwd != credentials[username]:
print("用户名或密码错误,请重新输入!")
else:
print("登录成功,欢迎您!")
break

def ui(credentials):
while True:
choice = input('''(0) Register
(1) Login
(2) Exit
请输入您的选择(0/1/2): ''').strip()

    if choice == "0":  
        register(credentials)  
    elif choice == "1":  
        login(credentials)  
    elif choice == "2":  
        print("拜拜,欢迎下次光临~")  
        break  
    else:  
        print("非法操作,请按要求输入!!!")  

if name == 'main':
credentials = read_credentials()
ui(credentials)

1个月前 评论

当然,我们可以对代码进行一些改进,使其更加优雅和可读。这里是一些建议的改进:

  1. 使用getpass模块来安全地获取密码,这样密码在输入时不会显示在屏幕上。
  2. 对文件操作进行异常处理,以防文件不存在或无法打开。
  3. 优化用户输入的处理,减少重复代码。
  4. 使用更具描述性的变量名
  5. 将UI与其他逻辑分离,使其更加模块化。

下面是改进后的代码:

import getpass

def write_credentials(username, passwd, filename="user_passwd.txt"):
    try:
        with open(filename, mode="a") as file:
            file.write(f"{username}: {passwd}\n")
    except Exception as e:
        print(f"Error writing to file: {e}")

def read_credentials(filename="user_passwd.txt"):
    credentials = {}
    try:
        with open(filename, mode="r") as file:
            for line in file:
                username, passwd = line.strip().split(":", 1)
                credentials[username.strip()] = passwd.strip()
    except FileNotFoundError:
        pass  # Ignore if file doesn't exist
    except Exception as e:
        print(f"Error reading from file: {e}")
    return credentials

def register(credentials):
    while True:
        username = input("请输入用户名:").strip()
        if username in credentials:
            print("用户已存在,请重新输入!")
        else:
            passwd = getpass.getpass("请设置密码:")  # Password won't be shown on the screen
            write_credentials(username, passwd)
            print("恭喜您,注册成功!")
            break

def login(credentials):
    while True:
        username = input("用户名:").strip()
        passwd = getpass.getpass("密码:")  # Password won't be shown on the screen
        if username not in credentials or passwd != credentials[username]:
            print("用户名或密码错误,请重新输入!")
        else:
            print("登录成功,欢迎您!")
            break

def ui(credentials):
    while True:
        choice = input('''(0) Register
(1) Login
(2) Exit
请输入您的选择(0/1/2): ''').strip()

        if choice == "0":
            register(credentials)
        elif choice == "1":
            login(credentials)
        elif choice == "2":
            print("拜拜,欢迎下次光临~")
            break
        else:
            print("非法操作,请按要求输入!!!")

if __name__ == '__main__':
    credentials = read_credentials()
    ui(credentials)

注意:这里使用了getpass模块来安全地获取密码输入。但是,密码仍然是以明文形式存储在文件中的,这在实际应用中是不安全的。为了增加安全性,您应该考虑使用加密或哈希技术来存储密码。此外,对于更复杂的用户管理系统,您可能会想使用数据库而不是文本文件来存储用户信息。

1个月前 评论
huanlemanong (楼主) 1个月前

学到了,感谢大神指点... :+1:

1个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!