In this blog, we will search some text or string in the multiple files.
text = input("Please enter text: ")
print(f"You have entered \"{text}\" word to search.")
OS module in Python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
import os
current_path = os.getcwd()
current_path
path = 'G:/data/input'
path
Create a function and change the directory in which you want to search text. After that list the directory and print the files.
os.listdir(path='.')
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.
def searchText(path):
os.chdir(path)
files = os.listdir()
print(files)
pass
searchText(path)
We got the list of files and folders.
def searchText(path):
os.chdir(path)
files = os.listdir()
#print(files)
for file_name in files:
print(file_name)
pass
searchText(path)
def searchText(path):
os.chdir(path)
files = os.listdir()
#print(files)
for file_name in files:
#print(file_name)
abs_path = os.path.abspath(file_name)
print("Absolute path of the file:", abs_path)
pass
searchText(path)
You can see, we have samples folder. In that folder also, we have to list the files. For that we need to do recursive search.
def searchText(path):
os.chdir(path)
files = os.listdir()
#print(files)
for file_name in files:
#print(file_name)
abs_path = os.path.abspath(file_name)
print("Absolute path of the file: ", abs_path)
if os.path.isdir(abs_path):
searchText(abs_path)
pass
searchText(path)
def searchText(path):
os.chdir(path)
files = os.listdir()
#print(files)
for file_name in files:
#print(file_name)
abs_path = os.path.abspath(file_name)
if os.path.isdir(abs_path):
searchText(abs_path)
if os.path.isfile(abs_path):
with open(file_name, 'r', encoding='utf-8') as f:
if text in f.read():
final_path = os.path.abspath(file_name)
print(text + " word found in this path " + final_path)
else:
print("No match found in " + abs_path)
pass
searchText(path)