0

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 against the external file solved.txt and displays an appropriate ‘success’ or ‘fail’ message.
if ''.join(open('test.txt').read().split('\n')):
    print('Success')
else:
    print('Fail')
    print()
    #If the puzzle has not been completed correctly, the user should be allowed to continue to try to solve the puzzle or exit the program.
    continue_or_exit = input('Would you like to "continue" or "exit"? ')
    if continue_or_exit == 'continue':
       task3(word_lines, clueslistl, clueslists, clues)
    elif continue_or_exit == 'exit':
        quit()
    else:
        print()

However, this does not work. Even if the string and the text file are exactly the same, the command prompt will always print 'Fail'.

solved.txt:

ACQUIRED
ALMANAC
INSULT
JOKE
HYMN
GAZELLE
AMAZON
EYEBROWS
AFFIX
VELLUM
6
  • 1
    It won't work for sure :D Commented Jun 3, 2014 at 17:18
  • What is the reasoning behind this? Commented Jun 3, 2014 at 17:18
  • 1
    What is text and text.txt? What is str (if not the builtin type)? Commented Jun 3, 2014 at 17:24
  • What's inside solved.txt? Commented Jun 3, 2014 at 17:35
  • The User is entering letter and symbol pairings ('A#') in order to change a list of coded words into words. The coded words has been made into a list in order to change and delete certain characters (''join). Commented Jun 3, 2014 at 17:35

1 Answer 1

7

Instead of that, do the following:

if string == 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.

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

2 Comments

''.join(open('test.txt').read().split('\n')) works, however it infinitely prints 'Success'?
Just add break after the print("Success").

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.