首页 > 解决方案 > 使用while循环检查文件中是否存在字符串

问题描述

我是 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()

如果我输入密码文件中存在的用户名,程序会提示我输入另一个用户名;但是,当我输入相同的用户名时,程序不会停留在循环中。关于为什么会发生这种情况的任何想法?

标签: python

解决方案


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

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

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()

推荐阅读