繁体   English   中英

使用while循环检查文件中是否存在字符串

[英]Checking if string exists in file using while loop

我是Python新手,在检查文件中的字符串时遇到循环麻烦。 对于此程序,我正在检查用户想要创建的用户名是否已经存在。 如果文件中已经存在用户名,程序将提示用户输入另一个用户名。 当用户输入不在文件中的用户名时,循环结束。 以下是相关代码:

# Prompting for username and password
username = input("Enter your username: ")
password = input("Enter your password: ")

# open password file
f = open("password.txt", "r")

# while username exists in file
while username in f.read():
    username = input("Enter your username: ")

f.close()

如果输入密码文件中存在的用户名,则程序会提示我输入另一个用户名; 但是,当我输入相同的用户名时,该程序不会停留在循环中。 为什么会这样?

没有条件检查新用户名是否在文件中。

也许更简单的方法是使用以下方法?

username = input("Enter your username: ")
password = input("Enter your password: ")

# open password file
f = open("password.txt", "r")
data = f.read()

# while username exists in file
while username in data:
    new = input("Enter your username: ")
    if new in data:
        continue
    else:
        break

username = new
f.close()

当您运行f.read() Python将读取文件,然后在下一次迭代中继续到文件的下一行。 它不会回到文件的顶部。 由于文件下一行中的username是空字符串或其他名称,因此它退出循环。 要解决此问题,您可以使用上下文管理器,如下所示:

# Prompting for username and password
username = input("Enter your username: ")
password = input("Enter your password: ")

# read in the file data
with open('password.txt') as f:
    data = f.read()

# while username exists in file
while username in data:
    username = input("Enter your username: ")

然后根据.txt文件中数据的结构,如果使用新行,则可以对data调用split()

这是因为您在while条件中使用了f.read()。 f.read一次读取文件的全部内容,没有其他东西可读取,导致while循环结束。

如果要检查文件中的用户名,建议您创建一个从文件中读取的用户名列表,并在while循环中使用它进行检查。

如果您的文件包含以下内容:username1,username2,...

你可以做

listOfUsernames = f.read().split(',')

然后使用它来检查while循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM