1

I made this to test it for another script. I have this code that checks if a specific value in users.txt I added it (let's say 21) exists the check function value 21 if it's, then it prints the existing value But no result with it, where is the problem?

listNum = list(range(1, 101))


def check(z):
    with open('users.txt') as f:
        for i in range(len(listNum)): 
            if str(i) in f.read():
                result = print(str(listNum[i]))
                return result

check(21)
4
  • 1
    You don't do anything with the returned value. And print() returns None, so result is None in any case. Commented Jul 4, 2021 at 10:43
  • 1
    @Guy Can you please give a small example, I'm fresh at python Commented Jul 4, 2021 at 10:49
  • can you share a file example and the precise expected output ? Commented Jul 4, 2021 at 10:49
  • 1
    @azro the file example has one value which is 21, The output must be the value that is in the example file Commented Jul 4, 2021 at 10:54

1 Answer 1

1

The problem is, that you consume the text file each time you perform f.read(). So in your loop you are not checking if all your numbers are in the file, but only if the very first is in your file, because for the seconds and all following numbers your f.read will result in an empty string, because the end-of-file was already reached.

Try storing the file content instead, like this:

def check(z):
    with open('users.txt') as f:
        file_content= f.read()
    for i in range(len(listNum)): 
        if str(i) in file_content:
            result = str(listNum[i])
            print(result)
            return result

check(21)

Btw. you don't need to use range objects to iterate over lists. It's more pythonic to do it like this:

def check(z):
    with open('users.txt') as f:
        file_content= f.read()
    for num in listNum: 
        if str(num) in file_content:
            result = print(num)
            return str(num)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, There's a little small problem, if there's a value like 32 in users.txt it takes only 3 value. How can I fix that
You mean, 3 also matches 32? there are more possibilities to solve that and it depens on the format of your input file which is the best / most convenient to do so. If it is a comma separated list of numbers you can parse it like that, if it is something like a plain text file that contains numbers, you'd probably better use regular expressions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.