Python search for input in txt file

…衆ロ難τιáo~ 提交于 2019-12-13 22:48:59

问题


When my script is run, it asks for an input. That input is then checked to see if it's in a text file. If it is, text is printed. The code I have below is what I have but it doesn't seem to be working, any help would be greatly appreciated!

discordname = input("What's your discord name?: ")
file = open('rtf.txt')
for line in file:
    line.strip().split('/n')
    if line.startswith(discordname):

        file.close()
        print("works")

回答1:


The expression

line.strip().split('\n')

is not mutating the information bound to the name line, which remains unchanged. Instead it returns a new value. You need to bind that new value to a name in order to use use it. This example might help:

In [1]: a = "  v  "

In [2]: a.strip()
Out[2]: 'v'

In [3]: a
Out[3]: '  v  '

In [4]: b = a.strip()

In [5]: a
Out[5]: '  v  '

In [6]: b
Out[6]: 'v'

Then split('\n') (note that you probably want \ instead of /) further returns a list of substrings split by newlines. Note that this is not very useful because for line in file: already splits over lines so the list would have one element at most, and so you should omit it.




回答2:


Here is the Solution:

discordname = input("What's your discord name?: ")
with open('rtf.txt', 'r') as f:
    for line in f.readlines():
        if line.startswith(discordname):
            print ("it works")

I hope it resolve you're problem.thanks




回答3:


You are probably trying to get strings as input as well. I suggest this:

discordname = raw_input("What's your discord name? ")
with open('rtf.txt') as f:
    for line in f:
        if discordname in line:
            print "works"



回答4:


You are trying to make the code more complex. Firstly to open a text file use 'with', because it is more flexible and doesn't need closing. Then, instead of using strip, you can use readlines(). This function converts each line into a list or you can also use method read(), which displays all results as it is.

So,

By using readlines, you can look through the user input in a line as a list, and by using read, you can look through each words. Here is the Solution:

discordname = input("What's your discord name? ")
with open('rtf.txt') as file:
       contents = file.readlines()
if discordname in contents:
       print("It exits")



回答5:


Works for me, Optimized code is:

result =  any(line.startswith(discordname) for line in file.splitlines())
if(result):
    file.close()
    print "works"


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

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