Austyn Howard
Austyn Howard

Reputation: 65

Search through multiple files/dirs for string, then print content of text file

I'm trying to make a small script that will allow me to search through text files located in a specific directory and folders nested inside that one. I've managed to get it to list all files in that path, but can't seem to get it to search for a specific string in those files and then print the full text file.

Code:

import os
from os import listdir
from os.path import isfile, join

path = "<PATH>"

for root, dirs, files in os.walk(path):
    for file in files:
        if file.endswith('.txt'):
            dfiles = str(file)

sTerm = input("Search: ")

for files in os.walk(path):
    for file in files:
        with open(dfiles) as f:
            if sTerm in f.read():
                print(f.read())

First part was from a test I did to list all the files, once that worked I tried using the second part to search through all of them for a matching string and then print the full file if it finds one. There's probably an easier way for me to do this.

Upvotes: 2

Views: 2567

Answers (1)

accdias
accdias

Reputation: 5372

Here is a solution with Python 3.4+ because of pathlib:

from pathlib import Path

path = Path('/some/dir')

search_string = 'string'

for o in path.rglob('*.txt'):
    if o.is_file():
        text = o.read_text()
        if search_string in text:
            print(o)
            print(text)

The code above will look for all *.txt in path and its sub-directories, read the content of each file in text, search for search_string in text and, if it matches, print the file name and its contents.

Upvotes: 2

Related Questions