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

当前回答

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

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

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

其他回答

两个问题:

你的函数没有返回任何东西;不显式返回任何内容的函数返回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"

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"需要在函数中作为全局变量创建,因为"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")

为什么你总是得到True的原因已经给出了,所以我只提供另一个建议:

如果你的文件不是很大,你可以把它读入一个字符串,然后使用它(比逐行读取和检查更容易,通常也更快):

with open('example.txt') as f:
    if 'blabla' in f.read():
        print("true")

另一个技巧:你可以通过使用mmap.mmap()来创建一个“类似字符串”的对象,使用底层文件(而不是在内存中读取整个文件)来缓解可能的内存问题:

import mmap

with open('example.txt') as f:
    s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    if s.find('blabla') != -1:
        print('true')

注意:在python 3中,mmap的行为更像bytearray对象而不是字符串,所以你用find()查找的子序列必须是一个bytes对象而不是字符串,例如。s.find (b 'blabla”):

#!/usr/bin/env python3
import mmap

with open('example.txt', 'rb', 0) as file, \
     mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    if s.find(b'blabla') != -1:
        print('true')

你也可以在mmap上使用正则表达式,例如,不区分大小写的搜索:if re.search(br'(?i)blabla', s):

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