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

当前回答

两个问题:

你的函数没有返回任何东西;不显式返回任何内容的函数返回None(这是假的) True始终为True—您不是在检查函数的结果

.

def check(fname, txt):
    with open(fname) as dataf:
        return any(txt in line for line in dataf)

if check('example.txt', 'blabla'):
    print "true"
else:
    print "false"

其他回答

两个问题:

你的函数没有返回任何东西;不显式返回任何内容的函数返回None(这是假的) True始终为True—您不是在检查函数的结果

.

def check(fname, txt):
    with open(fname) as dataf:
        return any(txt in line for line in dataf)

if check('example.txt', 'blabla'):
    print "true"
else:
    print "false"

这是另一个。获取绝对文件路径和给定字符串并将其传递给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)

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"
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"

check函数应该返回找到的布尔值,并使用它来确定要打印的内容。

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

        return found

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

第二部分也可以压缩为:

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