Skip to content Skip to sidebar Skip to footer

Python Search For Input In Txt File

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'

Solution 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.

Solution 2:

Here is the Answer :

discordname = input("What's your discord name?: ")
withopen('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

Solution 3:

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

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

Solution 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? ")
withopen('rtf.txt') as file:
       contents = file.readlines()
if discordname in contents:
       print("It exits")

Solution 5:

Works for me, Optimized code is:

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

Post a Comment for "Python Search For Input In Txt File"