我想检查一个字符串是否在文本文件中。如果是,执行x。如果不是,执行y。然而,由于某种原因,这段代码总是返回True。有人能看出哪里不对吗?

def check():
    datafile = file('example.txt')
    found = False
    for line in datafile:
        if blabla in line:
            found = True
            break

check()
if True:
    print "true"
else:
    print "false"

当前回答

"found"需要在函数中作为全局变量创建,因为"if else"语句不在函数中。您也不需要使用“break”来中断循环代码。 下面的方法可以确定文本文件是否有所需的字符串。

with open('text_text.txt') as f:
    datafile = f.readlines()


def check():
    global found
    found = False
    for line in datafile:
        if 'the' in line:
            found = True


check()

if found == True:
    print("True")
else:
    print("False")

其他回答

if True:
    print "true"

这种情况经常发生,因为True总是True。

你想要这样的东西:

if check():
    print "true"
else:
    print "false"

好运!

这里有另一种可能回答你的问题的方法,使用find函数,它给你一个文字数值,告诉你某物真正在哪里

open('file', 'r').read().find('')

在find中写下你想要找到的单词 'file'代表你的文件名

如果用户想在给定的文本文件中搜索单词。

 fopen = open('logfile.txt',mode='r+')

  fread = fopen.readlines()

  x = input("Enter the search string: ")

  for line in fread:

      if x in line:

          print(line)
found = False
def check():
datafile = file('example.txt')
for line in datafile:
    if "blabla" in line:
        found = True
        break
return found

if check():
    print "found"
else:
    print "not found"

我为此做了一个小函数。它在输入文件中搜索单词,然后将其添加到输出文件中。

def searcher(outf, inf, string):
    with open(outf, 'a') as f1:
        if string in open(inf).read():
            f1.write(string)

Outf是输出文件 Inf是输入文件 String当然是您希望找到并添加到outf的所需字符串。