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

时间:2014-06-03 17:17:12

标签: 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')):
    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()

然而,这不起作用。即使字符串和文本文件完全相同,命令提示符也会始终打印“失败”。

solved.txt:

ACQUIRED
ALMANAC
INSULT
JOKE
HYMN
GAZELLE
AMAZON
EYEBROWS
AFFIX
VELLUM

1 个答案:

答案 0 :(得分:4)

而不是这样做,请执行以下操作:

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',那么只需致电''.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.'
>>> 

' '.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. '
>>> 

另外,请勿使用str作为变量名称。它会影响内置功能。<​​/ strong>