Python3在txt文件中搜索输入

时间:2018-04-28 10:29:06

标签: python python-3.x scripting

基本上我想要实现的就是这个。我有一个文本文件,里面只有单词test。当脚本运行时,它会弹出一个输入,用户会编写测试。然后检查该输入以查看它是否在文本文件中,如果是,则打印工作,如果该输入不在文本文件中,则打印不起作用。以下代码无效。当我输入test作为输入时,我刚在终端中收到9行,每行说不起作用。正如我所说,测试这个词是文本文件中唯一的东西。任何帮助表示赞赏!!

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

2 个答案:

答案 0 :(得分:-1)

line.strip()不在原位;它返回剥离的线。试试line = line.strip()

无关建议:使用上下文管理器打开/关闭文件:

with open("rtf.txt") as file:
    for line in file:
       ...
# No need to call `file.close()`, it closes automatically here

这对我有用:

find_name.py:

name = input("What's your name? ")
with open("names.txt") as file:
    for line in file:
        if line.strip().startswith(name):
            print("Found name!")
            break
        else:
            print("Didn't find name!")

names.txt中:

foo
bar
baz
$ python3 find_name.py
What's your name? bar
Didn't find name!
Found name!

答案 1 :(得分:-1)

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