Keithx
Keithx

Reputation: 3148

Python Text Searching in .txt files in different folders with printing the name of file and folder

I'm making a script in Python for searching for the selected term (word/couple words, sentence) in a bunch of .txt files in a selected folder with printing out the names of the .txt files which contain the selected term. Currently is working pretty fine using os module:

import os

dirname = '/Users/User/Documents/test/reports'

search_terms = ['Pressure']
search_terms = [x.lower() for x in search_terms]

for f in os.listdir(dirname):
    with open(os.path.join(dirname,f), "r", encoding="latin-1") as infile:
        text =  infile.read()

    if all(term in text for term in search_terms):
        print (f)

But I wanna make the extension for the script: to be able to search not only in one folder (dirname), but in two for example (dirname1, dirname2) which consist of also .txt files. Also I would like to print not only the name of the searched report but the name of the directory (dirname) where it locates. Is it possible to do that using os module or there will be some other approaches to do that?

Upvotes: 0

Views: 233

Answers (1)

Igor S
Igor S

Reputation: 224

You can iterate over dirnames like this :

import os

dirnames = ['/Users/User/Documents/test/reports','/Users/User/Documents/test/reports2']

search_terms = ['Pressure']
search_terms = [x.lower() for x in search_terms]
for dir_name in dirnames:
    for f in os.listdir(dir_name):
        with open(os.path.join(dir_name, f), "r", encoding="latin-1") as infile:
            text = infile.read()

        if all(term in text for term in search_terms):
            print("{} in {} directory".format(f, dir_name))

Upvotes: 1

Related Questions