How to search a string in text files?

I want to check if a string is in a text file. If so, do X. If it is not, do Y. However, this code always returns True for some reason. Can anyone understand what is wrong?

 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" 
+143
python
Feb 09 2018-11-11T00:
source share
10 answers

The reason you always got True has already been indicated, so Iโ€™ll just offer another suggestion:

If your file is not too large, you can read it in a line and just use it (easier and often faster than reading and checking a line in a line):

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

Another trick: you can fix possible memory problems by using mmap.mmap() to create a "string" object that uses the base file (instead of reading the entire file in memory):

 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') 

NOTE: in python 3 mmaps behave like bytearray objects, not like strings, so the subsequence you are looking for with find() should also be a bytes object, not a string, for example. 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') 

You can also use regular expressions in mmap , for example, case insensitive search: if re.search(br'(?i)blabla', s):

+335
Feb 09 2018-11-12T00:
source share

As Jeffrey Said said, you are not checking the value of check() . In addition, your check() function returns nothing. Please note the difference:

 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 

Then you can check the output of check() :

 if check(): print('True') else: print('False') 
+26
Feb 09 2018-11-11T00:
source share

Here's another way to answer your question using the find function, which gives you a literal numeric value where something really is

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

in the search write the word you want to find and 'file' means your file name

+17
Nov 26 '12 at 1:26
source share
 if True: print "true" 

This always happens because True is always right.

You want something like this:

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

Good luck

+12
Feb 09 '11 at 0:10
source share

Your check function should return the boolean found and use this to determine what to print.

 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" 

the second block could also be condensed to:

 if check(): print "true" else: print "false" 
+4
Feb 09 2018-11-11T00:
source share

I made a small function for this purpose. It searches for a word in the input file and then adds it to the output file.

 def searcher(outf, inf, string): with open(outf, 'a') as f1: if string in open(inf).read(): f1.write(string) 
  • outf is the output file
  • inf is the input file String
  • - this, of course, is the search string you want to find and add to outf.
+4
May 01 '15 at 7:49
source share

Two problems:

  • Your function returns nothing; a function that explicitly returns nothing returns None (which is false)

  • True is always True - you do not check the result of your function

.

 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" 
+2
Feb 09 2018-11-11T00:
source share

How to search for text in a file and returns the path to the file in which the word is located (How to search for part of the text in the file and return the path to the file in which the word is found)

 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 

In the 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 
+2
Aug 23 '13 at 7:48 on
source share

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" 
+1
Feb 09 2018-11-11T00:
source share

If the user wants to find a word in this text file.

  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) 
+1
May 18 '19 at 8:00
source share



All Articles