简体   繁体   English

Python3在txt文件中搜索输入

[英]Python3 search for input in txt file

Basically what I want to achieve is this. 基本上我想实现的是这个。 I have a text file with only the word test in it. 我有一个仅包含单词test的文本文件。 When the script is run it pops up with an input and the user would write test. 运行脚本时,它将弹出一个输入,用户将编写测试。 That input is then checked to see if its in the text file and if it is, it would print works, and if that input isn't in the text file, it would print doesn't work. 然后检查该输入以查看其是否在文本文件中,如果输入正确,则将打印正常;如果该输入不在文本文件中,则无法打印。 The code below is not working. 下面的代码不起作用。 When I type test as my input, I just received 9 lines in the terminal each saying doesn't work. 当我输入test作为输入时,我在终端中仅收到9行,每行都无效。 As I said, the word test is the only thing in the text file. 如我所说,单词test是文本文件中唯一的内容。 Any help is appreciated!! 任何帮助表示赞赏!

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

line.strip() is not in-place; line.strip()不在适当位置; it returns the stripped line. 它返回剥线。 Try line = line.strip() . 尝试line = line.strip()

Unrelated advice: use a context manager to open / close the file: 不相关的建议:使用上下文管理器打开/关闭文件:

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

This works as expected for me: 这对我来说是预期的:

find_name.py: 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: names.txt:

foo
bar
baz

$ python3 find_name.py
What's your name? bar
Didn't find name!
Found name!
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")

Just try this. 尝试一下。 it works. 有用。 Or if you want to check on every word try read() instead of readlines() 或者,如果您想检查每个单词,请尝试使用read()而不是readlines()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM