Python-将字符串与文本文件进行比较

Python-将字符串与文本文件进行比较,python,python-3.x,Python,Python 3.x,在IF语句中,我有一个字符串,希望将其与文本文件进行比较。目前我有以下几点: #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')):

在IF语句中,我有一个字符串,希望将其与文本文件进行比较。目前我有以下几点:

    #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()
if string == open('myfile.txt').read():
    print('Success')
else:
    print('Fail')
然而,这是行不通的。即使字符串和文本文件完全相同,命令提示符也将始终打印“Fail”

solved.txt:

ACQUIRED
ALMANAC
INSULT
JOKE
HYMN
GAZELLE
AMAZON
EYEBROWS
AFFIX
VELLUM

相反,请执行以下操作:

    #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()
if string == open('myfile.txt').read():
    print('Success')
else:
    print('Fail')
这使用内置函数
open()
.read()
从文件中获取文本

但是,
.read()
将导致如下结果:

>>> x = open('test.txt').read()
>>> x
'Hello StackOverflow,\n\nThis is a test!\n\nRegards,\nA.J.\n'
>>> 
因此,请确保您的字符串包含必要的
'\n'
s(换行符)

如果字符串不具有
'\n'
s,则只需调用
'.join(open('test.txt').read().split('\n'))

'.join(打开('test.txt').read().split('\n'))


另外,不要将
str
用作变量名。它隐藏了内置的功能。

它肯定不起作用:数据背后的原因是什么?什么是
text
text.txt
?什么是
str
(如果不是内置类型)?solved.txt内部是什么?用户输入字母和符号配对('A#'),以便将编码单词列表更改为单词。已将编码的单词编入列表,以便更改和删除某些字符(“join”)。“”.join(open('test.txt').read().split('\n'))可以工作,但是它会无限打印“Success”?只需在
打印(“Success”)
之后添加
break