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

为什么你总是得到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):

if True:
    print "true"

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

你想要这样的东西:

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"

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

 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)