首页 > 解决方案 > 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")

标签: pythonpython-3.xscripting

解决方案


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


推荐阅读