Home > OS >  Python search files in multiple subdirectories for specific string and return file path(s) if presen
Python search files in multiple subdirectories for specific string and return file path(s) if presen

Time:11-06

I would be very grateful indeed for some help for a frustrated and confused Python beginner.

I am trying to create a script that searches a windows directory containing multiple subdirectories and different file types for a specific single string (a name) in the file contents and if found prints the filenames as a list. There are approximately 2000 files in 100 subdirectories, and all the files I want to search don't necessarily have the same extension - but are all in essence, ASCII files.

I've been trying to do this for many many days but I just cannot figure it out.

So far I have tried using glob recursive coupled with reading the file but I'm so very bewildered. I can successfully print a list of all the files in all subdirectories, but don't know where to go from here.

import glob
files = []
files = glob.glob('C:\TEMP'   '/**', recursive=True)
print(files)

Can anyone please help me? I am 72 year old scientist trying to improve my skills and "automate the boring stuff", but at the moment I'm just losing the will.

Thank you very much in advance to this community.

CodePudding user response:

great to have you here!

What you have done so far is found all the file paths, now the simplest way is to go through each of the files, read them into the memory one by one and see if the name you are looking for is there.

import glob
files = glob.glob('C:\TEMP'   '/**', recursive=True)

target_string = 'John Smit'

# itereate over files
for file in files:
    try:
        # open file for reading
        with open(file, 'r') as f:
            # read the contents
            contents = f.read()
        # check if contents have your target string
        if target_string in conents:
            print(file)
    except:
        pass

This will print the file path each time it found a name.

Please also note I have removed the second line from your code, because it is redundant, you initiate the list in line 3 anyway.

Hope it helps!

CodePudding user response:

You could do it like this, though i think there must be a better approach

When you find all files in your directory, you iterate over them and check if they contain that specific string.

for file in files:
    if(os.path.isfile(file)):
        with open(file,'r') as f:
            if('search_string' in f.read()):
                print(file)
  • Related