我想检查一个字符串是否在文本文件中。如果是,执行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 = False

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

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

其他回答

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

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

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

if True:
    print "true"

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

你想要这样的东西:

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

好运!

正如Jeffrey所说,您不是在检查check()的值。此外,check()函数没有返回任何东西。注意区别:

def check():
    with open('example.txt') as f:
        datafile = f.readlines()
    found = False  # This isn't really necessary
    for line in datafile:
        if blabla in line:
            # found = True # Not necessary
            return True
    return False  # Because you finished the search without finding

然后你可以测试check()的输出:

if check():
    print('True')
else:
    print('False')

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

 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)

这是另一个。获取绝对文件路径和给定字符串并将其传递给word_find(),在enumerate()方法中对给定文件使用readlines()方法,该方法在逐行遍历时给出可迭代计数,最终为您提供具有匹配字符串的行,加上给定的行号。欢呼。

  def word_find(file, word):
    with open(file, 'r') as target_file:
        for num, line in enumerate(target_file.readlines(), 1):
            if str(word) in line:
                print(f'<Line {num}> {line}')
            else:
                print(f'> {word} not found.')


  if __name__ == '__main__':
      file_to_process = '/path/to/file'
      string_to_find = input()
      word_find(file_to_process, string_to_find)