Searching Text Strings from Files Using Python
Searching text strings from files in a given folder is easily accomplished by using Python in Windows. While Linux has the grep command, Windows does not have an equivalent. The only alternative, then, is to make a command that will search the string. Thi
Have you ever thought of searching a string in the files of a given folder? If you are a Linux lover, you must be thinking about the grep command. But in Windows, there is no grep command. By using Python programming, you can make your own command which will search the string pattern from the given files. The program also offers you the power of regular expressions to search the pattern.
In this article, I am going to show you an amazing utility, which will help you to find the string from a number of files.
The program, see.py, will search for the string pattern provided by the user, from the files presented in the directory, also given by the user. This is equivalent to the grep command in the Linux OS. Here, we will use Python 2.7.
The program expects the string pattern and directory from the user. Let us examine the code and discuss it.
Import the mandatory modules import os import re import sys import argparse
In the following code I have declared a class Text_search class Text_search :
def __init__(self, string2, path1,i=None): self.path1= path1 self.string1 = string2 self.i=i if self.i:
string2 = string2.lower() self.string2= re.compile(string2)
The following method gives the file’s name in which the given string is found:
def txt_search(self): file_number = 0 files = [f for f in os.listdir(self.path1) if os.path. isfile(self.path1+”/”+f)] for file in files: file_t = open(self.path1+”/”+file) file_text= file_t.read() if self.i:
file_text=file_text.lower() file_t.close() if re.search(self.string2, file_text):
print “The text “+self.string1+” found in “,
file
file_number=file_number+1 print “total files are “,file_number