Skip to content Skip to sidebar Skip to footer

Python 2.7 Script - Searching For A String In All Files In Directories And Sub-Directories

I have a folder named documents, within that I have 3,000 text files and two sub directories: which contains more thousands of text files. I'm trying to code it so that it searche

Solution 1:

At least for me glob.glob() only searched through the top level directory.

import os
import glob

# Sets the main directory
main_path = "C:\\Users\\Dawn Philip\\Documents\\documents"

# Gets a list of everything in the main directory including folders
main_directory = os.listdir(main_path)

# This list will hold all of the folders to search through, including the main folder
sub_directories = []

# Adds the main folder to to the list of folders
sub_directories.append(main_path)

# Loops through everthing in the main folder, searching for sub folders
for item in main_directory:
    # Creates the full path to each item)
    item_path = os.path.join(main_path, item)

    # Checks each item to see if it is a directory
    if os.path.isdir(item_path) == True:
        # If it is a folder it is added to the list
        sub_directories.append(item_path)

for directory in sub_directories:
    for files in glob.glob(os.path.join(directory,"*.txt")):
        f = open( files, 'r' )
        file_contents = f.read()
        if "x" in file_contents:
            print f.name

Post a Comment for "Python 2.7 Script - Searching For A String In All Files In Directories And Sub-Directories"