简体   繁体   中英

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. 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. As I said, the word test is the only thing in the text file. 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; it returns the stripped line. Try 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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