0

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?

Keithx
  • 2,994
  • 15
  • 42
  • 71

1 Answers1

1

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))
Igor S
  • 224
  • 3
  • 11
  • it seems that this script shows only the first one file consisting the information from each folder and not all of them – Keithx Jul 15 '18 at 22:02
  • @HalfPintBoy Is it possible that only first file fits the condition? – Igor S Jul 15 '18 at 22:07
  • so for example, I checked it when put all the files in one folder with same search term it gives me 10 matches, when I do it in two different folders (same files) the result is only one match from each folder. – Keithx Jul 15 '18 at 22:11