python - 如何让程序继续在文件中搜索另一个用户名?
问题描述
我正在尝试在 Repl.it 中完成我的 Python 代码的登录过程。它将搜索名为“UDfile”的 csv 文件以确认用户名和密码,以便它可以访问我正在创建的纸牌游戏。这是文件的样子:
markd,12345
pltwo,67890
forhb,10\/3
但是,我正在为 2 个用户创建这个。只要我输入的用户名高于第二个人的用户名,登录第一个人就可以正常工作。但是当我尝试输入第二个用户名时,无论正确与否,它总是会说它无法识别用户名。我怀疑它没有进行完整的搜索。我怎样才能让它彻底搜索这个 csv 文件,以便它允许我输入 P2 的密码,从而继续程序?
我在stackoverflow中搜索“当它说它不存在时如何让这个代码找到现有用户名?”的内容。但我什么也找不到。
我也尝试添加
系统退出
到结束
print("未找到用户名")
在 user_findtwo(file, user) 中,希望它会彻底搜索文件并仅在完全找不到它时终止,但是在程序说一次找不到它之后会立即结束代码。
最后,我尝试了一个while循环说
while row[0] != usertwo:
print("Username not found")
sys.exit()
我希望它只搜索整个文本文件并说“找不到用户名”,直到找到玩家二的用户名,但它只是无休止地打印“找不到用户名”。
import csv
import sys
def main():
login()
logintwo()
show_menu()
menu_choice = int(input("Welcome to the RYG card game! Press \"1\" and then \"Enter\" to play a game:"))
options(menu_choice)
def login():
with open("UDfile", "r") as file:
file_reader = csv.reader(file)
user_find(file_reader)
file.close
def user_find(file):
user()
for row in file:
if row[0] == user:
print("Username is found:", user)
user_found = [row[0], row[1]]
pass_check(user_found)
break
else:
print("Username not found")
sys.exit()
def user():
global user
user = input("Player 1, enter your username (must be above player 2's desired name):")
def logintwo():
with open("UDfile", "r") as file:
file_reader = csv.reader(file)
user_findtwo(file_reader, user)
file.close
def user_findtwo(file, user):
usertwo = input("Player 2 enter your name:")
if usertwo == user:
print("Usernames must be different. Restart the program.")
sys.exit()
else:
for row in file:
if row[0] == usertwo:
print("Username is found:", usertwo)
user_found = [row[0],row[1]]
pass_checktwo(user_found)
break
else:
print("Username not found")
def pass_check(user_found):
x = True
while x:
user = input("Enter your password:")
if user_found[1] == user:
print("Password match.")
x = False
else:
print("Password doesn't match.")
sys.exit()
def pass_checktwo(user_found):
y = True
while y:
usertwo = input("Player 2 enter your password:")
if user_found[1] == usertwo:
print("Password match.")
y = False
else:
print("Password doesn't match.")
sys.exit()
请参阅背景以了解预期和实际结果。
解决方案
你能用这个方法循环遍历行吗?您可以使用 len(csvFileArray) 来获取长度,让它循环到最大值以避免索引超出范围,并且一旦找到它需要的东西就可以让它传递函数(所以它不会继续循环吗?)
https://stackoverflow.com/a/39629619
只是一个快速的想法
推荐阅读
- javascript - 用锚标记替换字符串的多个部分
- javascript - 如何为 AWS CloudFormation 堆栈和资源实施区域特定配置
- database - 使用 go-pg 从 Postgres 中检索虚拟列
- python - Django:如何根据 order_id 获取 order_detail_data
- perl - Perl 证书认证
- c# - 如何减少大量 combobox.selecteditem 属性的样板代码
- c# - C# 仅从 localhost 访问自托管 WCF 登录页面
- ruby - 使用 IRB.conf 设置自定义 .irbrc 的路径
- swift - AVAudioPCMBuffer 只能获取带有静态/白噪声的音频
- excel - 如何在 Excel 中生成具有偏态正态分布的随机数?