检查文本文件python中是否存在word

检查文本文件python中是否存在word,python,search,Python,Search,我正在使用Python,并试图找出文本文件中是否有单词。我正在使用此代码,但它总是打印“未找到单词”,我认为该条件中存在一些逻辑错误,如果您可以更正此代码,请联系任何人: file = open("search.txt") print(file.read()) search_word = input("enter a word you want to search in file: ") if(search_word == file): print("wo

我正在使用Python,并试图找出文本文件中是否有单词。我正在使用此代码,但它总是打印“未找到单词”,我认为该条件中存在一些逻辑错误,如果您可以更正此代码,请联系任何人:

file = open("search.txt")
    print(file.read())
    search_word = input("enter a word you want to search in file: ")
    if(search_word == file):
        print("word found")
    else:
        print("word not found")

以前,您在文件变量中搜索,该变量为“open”(“search.txt”)。由于该变量不在您的文件中,因此您将无法找到word

由于==,您还询问搜索词是否与“open”(“search.txt”)完全匹配。不要使用==,而是使用“in”。尝试:

file = open("search.txt")
strings = file.read()
print(strings)
search_word = input("enter a word you want to search in file: ")
if(search_word in strings):
    print("word found")
else:
    print("word not found")

最好您在打开文件时习惯于使用
,这样,当您使用完文件后,它会自动关闭。但最主要的是在中使用
在另一个字符串中搜索字符串

with open('search.txt') as file:
    contents = file.read()
    search_word = input("enter a word you want to search in file: ")
    if search_word in contents:
        print ('word found')
    else:
        print ('word not found')

另一种选择是,您可以在读取文件本身时进行
搜索

search_word = input("enter a word you want to search in file: ")

if search_word in open('search.txt').read():
    print("word found")
else:
    print("word not found")

要缓解可能的内存问题,请使用此处回答的
mmap.mmap()
搜索文件中的单词,而不是与文件相同的单词。尝试此
print(file.read())
将文件内容读入字符串,打印,然后丢弃。你不想那样做。您需要保存文件数据,例如
data=file.read()
。您应该在
操作符中阅读Python的
。@zhenguoli那么正确的条件应该是什么呢?