gpt4 book ai didi

python - 如何测试字典(在外部文件中)是否包含用户输入的用户名(Python3)?

转载 作者:行者123 更新时间:2023-11-28 19:20:40 26 4
gpt4 key购买 nike

我正在构建一个跳蚤市场程序。我有一个外部文件托管所有员工的用户名和密码。我正在尝试测试登录部分,要求输入用户名和密码。它测试 UN 是否在 readline() 包含的字典中。

这是包含用户名和密码的外部文件。 :

managers = {"manager":"password", "owner":"apple"}
employees = {"jane":"none", "john":"banana"}

代码如下:

print("Welcome to Flea Master 2000...\n")
read_employee_file = open('employees_list.txt', 'r')
managers = read_employee_file.readline(0)
employees = read_employee_file.readline(1)
print(managers)
read_employee_file.close()

user_id = input("User ID:\n")
user_password = input('Password:\n')
if user_id in managers[:]:
if managers[user_id] == user_password:
print("Welcome, {0}.".format (user_id))
user_status='manager'
if user_id in employees:
if employees[user_id] == user_password:
print("Welcome, {0}".format (user_id))
user_status = 'staff'
if user_status == 'manager':
action_manager = int(input("Options: (Input number to select...)\n1) Add employee.\n2) Remove employee.\n"))
if action_manager == 1:
employee_addition_type=input("What kind of employee is he/she? ('manager' or 'staff')")
if employee_addition_type == 'manager':
new_manager_username = input("Enter the new manager's username...\n")
new_manager_password = input("Enter the new manager's password...\n")
managers[new_manager_username] = new_manager_password
else:
new_staff_username = input("Enter the new staff member's username...\n")
new_staff_password = input("Enter the new staff member's password...\n")
employees[new_staff_username]=new_staff_password

if action_manager == 2:
print("The list of current employees is: \n")
for key in all_staff:
print(key)
print('\n')
which_remove = input("Now, which do you want to remove? Enter the username exactly.\n")
if which_remove in managers:
del managers[which_remove]
else:
del employees[which_remove]
print("\nDone. Updated roster is:\n")
all_staff = dict(managers, **employees)
for key in all_staff:
print(key
)

最佳答案

您的 readline 行有点不正确。 readlines 的参数是它将读取的最大字节数。所以readlines(6)并不是“读取第六行”的意思,而是“从当前行开始读取不超过六个字符”的意思。我建议只执行 read_employee_file.readline(),不带任何参数。

managers = read_employee_file.readline()
employees = read_employee_file.readline()

现在您拥有每一行的全部内容,但两个变量仍然是字符串。但是,您可以使用 json 模块来加载这些字典。

import json
line = 'managers = {"manager":"password", "owner":"apple"}'

#chop off the left part of the string containing "managers = "
line = line.partition(" = ")[2]
d = json.loads(line)

print "the owner's password is", d["owner"]

if "bob" not in d:
print "can't find bob's password in managers dictionary!"

结果:

the owner's password is apple
can't find bob's password in managers dictionary!

关于python - 如何测试字典(在外部文件中)是否包含用户输入的用户名(Python3)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25999825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com