0

I've been dealing with this part of the code, trying to get a possitive, but being unable to get one. After a while discovered that my function "if bola in open('users.txt'):" isn't trying to identify one part of the string, since it will only give me a possitive if users.txt only contains the word "Bola". I mean, if I write " Bola" inside user.txt it will give me a false. I managed to understand the problem, but don't know how to fix it. Tried using U.find() but it didn't work either... any solution will be apreciated...

thanks in advance

    U=open('users.txt','a+')
    bola = "Bola"
    if bola in open('users.txt'):
        U.close()
        print("usercid found")
    else:
        U.write("[" + str(cid) + "]"+str(m.from_user.first_name)+"\n")
        U.close()
        print("no usercid gaaaaa")
Bola
  • 19
  • 1
  • 1
  • 4

3 Answers3

3

open('users.txt') returns a generator that enumerates lines of the file, not a string containing the file content, and because of that if bola in open('users.txt') will return True if and only if there's an element in the generated sequence which matches bola.

For your use case you want to do the following:

if bola in open('users.txt').read():
    U.close()
    print("usercid found")

open(...).read() will return you a string that represents the entire file, and as such, bola in open(...).read() will return True if bola is contained in the file as a substirng, not necessarily as a line on its own.

This still has an issue (that your original code also has) that you leak a file descriptor that open creates. To avoid it, you can do something along the lines of:

with open('users.txt') as fr:
    if bola in fr.read():
        U.close()
        print("usercid found")
    else:
        ...
Ishamael
  • 12,583
  • 4
  • 34
  • 52
0

You can't find your string because open('users.txt') returns a list of strings, each of them with a new-line. Easiest solution is to search for bola = "Bola\n"

Or:

for line in open('file.txt'):
    if bola == line.rstrip():
        print("usercid found")
        break
kaspersky
  • 3,959
  • 4
  • 33
  • 50
  • you mean it returns each line like string1 string2 string3 ??? is there a way to find the string I need between the line? – Bola Jun 01 '16 at 05:25
  • @DiegoErósteguiNavia, open('file.txt') will return lines like "bola\n", but you compare with "bola". So you either remove the newline from each line, or add '\n' to your search query. – kaspersky Jun 01 '16 at 05:29
0
U=open('users.txt','a+')
bola = "Bola"
for line in open('users.txt'):
    if line.find(bola) >= 0:
        U.close()
        print("usercid found")
    else:
        U.write("[" + str(cid) + "]"+str(m.from_user.first_name)+"\n")
        U.close()
        print("no usercid gaaaaa")
atline
  • 28,355
  • 16
  • 77
  • 113