Python3 search for input in txt file

两盒软妹~` 提交于 2019-12-24 08:57:10

问题


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

回答1:


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!



回答2:


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



来源:https://stackoverflow.com/questions/50075502/python3-search-for-input-in-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!