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

0 投票
1 回答
19777 浏览
提问于 2025-04-18 08:27

在一个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 个回答

7

不要这样做,试试下面的方法:

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'(换行符)。

如果你的字符串没有 '\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 当作变量名使用。这样会覆盖掉内置的功能。

撰写回答