python - 使用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()
如果我输入密码文件中存在的用户名,程序会提示我输入另一个用户名;但是,当我输入相同的用户名时,程序不会停留在循环中。关于为什么会发生这种情况的任何想法?
解决方案
没有条件检查新用户名是否在文件中。
也许更简单的方法是使用以下方法?
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()
推荐阅读
- c - 计算和打印矩阵的对角线之和
- javascript - 如何在 Angular 中使用 addEventListener 和 postMessage?
- php - 如何将日期、时间和值从单选按钮放入数据库
- c# - 逐个像素地动态绘制和显示,有一些延迟
- npm - 如何从 Nexus oss 代理获取依赖于 github 项目的 npm 包
- django - Django 测试 - 发送包含整数的数组数组
- android - 在 android 中使用改造登录
- json - 我如何在 nunjuncks 中乘以数据?
- swift - 为什么不能在swift中将可变参数标记为inout?
- vue.js - Vue Js 2 / Vue-CLI 3 / 托管时显示空白页