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

当前回答

if True:
    print "true"

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

你想要这样的东西:

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

好运!

其他回答

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

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

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

如何搜索文件中的文本并返回在其中找到的字的文件路径 (Какискатьчастьтекставфайлеивозвращятьпутькфайлувкоторомэтословонайдено)

import os
import re

class Searcher:
    def __init__(self, path, query):
        self.path   = path

        if self.path[-1] != '/':
            self.path += '/'

        self.path = self.path.replace('/', '\\')
        self.query  = query
        self.searched = {}

    def find(self):
        for root, dirs, files in os.walk( self.path ):
            for file in files:
                if re.match(r'.*?\.txt$', file) is not None:
                    if root[-1] != '\\':
                        root += '\\'           
                    f = open(root + file, 'rt')
                    txt = f.read()
                    f.close()

                    count = len( re.findall( self.query, txt ) )
                    if count > 0:
                        self.searched[root + file] = count

    def getResults(self):
        return self.searched

在Main ()

# -*- coding: UTF-8 -*-

import sys
from search import Searcher

path = 'c:\\temp\\'
search = 'search string'


if __name__ == '__main__':

    if len(sys.argv) == 3:
        # создаем объект поисковика и передаем ему аргументы
        Search = Searcher(sys.argv[1], sys.argv[2])
    else:
        Search = Searcher(path, search)

    # начать поиск
    Search.find()

    # получаем результат
    results = Search.getResults()

    # выводим результат
    print 'Found ', len(results), ' files:'

    for file, count in results.items():
        print 'File: ', file, ' Found entries:' , count

两个问题:

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

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

你想要这样的东西:

if check():
    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):