python - Python3在txt文件中搜索输入
问题描述
基本上我想要实现的就是这个。我有一个文本文件,其中只有单词 test。当脚本运行时,它会弹出一个输入,用户将编写测试。然后检查该输入以查看它是否在文本文件中,如果是,它将打印工作,如果该输入不在文本文件中,它将打印不起作用。下面的代码不起作用。当我输入 test 作为输入时,我刚刚在终端中收到 9 行,每行都说不起作用。正如我所说,单词 test 是文本文件中唯一的内容。任何帮助表示赞赏!
discordname = input("What's your discord name?: ")
file = open('rtf.txt')
for line in file:
line.strip()
if line.startswith(discordname):
file.close()
print("works")
else:
print("doesn't work")
解决方案
discordname = input("What's your discord name? ")
with open('rtf.txt') as file:
contents = file.readlines()
if discordname in contents:
print("It exits")
else:
print("Doesnot exits")
试试这个。有用。或者,如果您想检查每个单词,请尝试使用 read() 而不是 readlines()
推荐阅读
- mongodb - Kubernetes mongodb 就绪探测失败
- c - 为什么我的#ifndef 预处理器指令在编译时不能防止包含多个标头?
- rust - 有没有办法将布尔值用作枚举的基础类型?
- html - 如何防止CSS动画在每个循环后重置
- azure - 枚举 Azure SQL Server 中的数据库列表
- android - 如何解决 Android Studio 3.2 上不存在指定的 AAPT2 可执行文件
- c++ - 通话中的参数太少
- python - 延迟文本时输出无结束
- python - 使用python将一个文件拆分为多个文件,其中包含一个关键字
- python - 如何映射两个字符串之间的差异?