Skip to content Skip to sidebar Skip to footer

Python - Compare A String With A Text File

Within an IF statement, I have a string and wish to compare it with a text file. Currently I have the following: #The part of the program that checks the user’s list of words

Solution 1:

Instead of that, do the following:

ifstring == open('myfile.txt').read():
    print('Success')
else:
    print('Fail')

This uses the built-in function open(), and .read() to get the text from a file.

However, the .read() will result in something like this:

>>>x = open('test.txt').read()>>>x
'Hello StackOverflow,\n\nThis is a test!\n\nRegards,\nA.J.\n'
>>>

So make sure your string contains the necessary '\n's (newlines).

If your string does not have the '\n's, then just call ''.join(open('test.txt').read().split('\n')):

>>>x = ''.join(open('test.txt').read().split('\n'))>>>x
'Hello StackOverflow,This is a test!Regards,A.J.'
>>>

Or ' '.join(open('test.txt').read().split('\n')):

>>>x = ' '.join(open('test.txt').read().split('\n'))>>>x
'Hello StackOverflow,  This is a test!  Regards, A.J. '
>>>

Also, don't use str as a variable name. It shadows the built-in.

Post a Comment for "Python - Compare A String With A Text File"