0

I want to check if a string is in a file or not, but i can't seem to get it to work.

file = open("test.txt","r+")

username = 'user'
password = 'password'

if username+password in file:
    print("true")
else:
    print("false")

and the file contains:

userpassword

it should output 'true' as 'username+password' should be equal to 'userpassword', but the output is 'false',what am I doing wrong here?

Jazz Handy
  • 15
  • 2

2 Answers2

0
file = open("test.txt","r+").read()

will return the file contents to file. Just doing file = open("test.txt","r+") will return a file-like object, you actually have to read the content of the file from the object.

miike3459
  • 1,431
  • 2
  • 16
  • 32
0

You've opened the file, but haven't read any of the content. Try using content = file.readlines() (also, try to avoid using file as a variable name - it's also a builtin function)

_file = open("test.txt","r+")

username = 'user'
password = 'password'

for line in _file.readlines():
    if username+password in file:
        print("true")
    else:
        print("false")
Andrew
  • 1,072
  • 1
  • 7
  • 15