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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.