Python 新手和第一次发帖者(但长期潜伏)在这里,对于任何格式或协议问题深表歉意。
我正在尝试编写一段代码来防止将重复的用户名写入文件。我已经尝试了论坛上以前类似问题的各种解决方案,但无济于事。
在迄今为止的最新迭代中,我已成功拒绝第一个密钥的重复项,但后续密钥的重复项仍在处理中。即,如果我的密钥具有值“admin”和“user”(我在第一个打印语句中已确认),则 x = admin 正确地被拒绝,但 x = users 仍在进行中。请帮忙
我的代码:
alr_exists = {}
user = {}
with open('user.txt', 'r') as file:
for lines in file:
(keys, values) = lines.split()
keys = keys.replace(',', '')
alr_exists[keys] = keys
print(alr_exists[keys])
while True:
x = input("To register a new user, please enter a username:\n").lower()
if x in alr_exists[keys]:
print(f'Sorry, the user name {x} has already been taken. Please try again.\n')
continue
else:
y = input("Please enter a password:\n").lower()
z = input("To confirm, please reenter your password:\n").lower()
样本数据集:
管理员,adm1n
用户,us3r
(其中第一列包含用户名和第二列密码)
我希望您喜欢使用 Python 编程。我也是新来的。
查看您的代码,我发现三件事可能导致其无法正常工作:
if x in alr_exists[keys]:
您可以在您的情况下使用 dict.keys() 函数if x in alr_exists.keys()
我提出了你的代码的修改版本,我希望它对你来说并不复杂,它也有注释并且遵循pep8的风格。
def read_existing_usernames(filename):
"""Read existing usernames from a file and store them in a dictionary.
Args:
filename (str): The name of the file containing existing usernames.
Returns:
dict: A dictionary containing existing usernames as keys.
"""
# Create an empty dictionary to store existing usernames
existing_usernames = {}
# Read existing usernames from the file
with open(filename, 'r') as file:
# Iterate over each line in the file
for line in file:
# Split the line into username and password (separated by a space)
username, _ = line.split()
# Store the username in the dictionary and set the value to True
existing_usernames[username] = True
# Print a success message with the existing usernames
print(f'Existing usernames: {', '.join(existing_usernames)}')
# Return the dictionary of existing usernames
return existing_usernames
def register_user():
"""
Register a new user by entering a username and password.
The username must be unique and the password must be confirmed.
The new username and password are stored in a file. ('user.txt')
Args:
None
Returns:
None
"""
# Bring in existing usernames from the file with the function
existing_usernames = read_existing_usernames('user.txt')
# Iterate until a new user is successfully registered
while True:
# Prompt the user to enter a new username
username = input("To register a new user, please enter a username: ")
# Check if the username is already taken
if username.lower() in existing_usernames:
# Print an error message and prompt the user to try again
print(f"Sorry, the username '{username}' has already been taken")
print("Please try again.\n")
# If the username is not taken
else:
# Prompt the user to enter a password and confirm it
password = input("Please enter a password: ")
# Confirm the password by reentering it
confirm_password = input("Please reenter your password: ")
# Check if the passwords match
if password == confirm_password:
# Open the file in append mode and write the new information
# Append because we don't want to overwrite the existing data
with open('user.txt', 'a') as file:
# Write the new username and password to the file
file.write(f'{username} {password}\n')
# Print a success register message
print("User registered successfully!")
# Break out of the loop to end the program
break
# If the passwords do not match
else:
# Print an error message and prompt the user to try again
print("Passwords do not match. Please try again.\n")
# Run main program to register a new user
register_user()