Search code examples
pythonfilesystemsglobsubdirectory

How to access files in multiple sub-directories using glob


I have several files stored in a folder called Originals. Originals is stored in a folder called B_Substrate, B_Substrate is stored in a folder called Substrate_Training and Substrate_Training is stored in a folder called Jacob_Images.

I am trying to access the files in the folder Originals using glob but unable to access them. Can anyone help me understand how to access files in multiple sub directories

This is my code but it doesn't work

import glob 
file = '/content/drive/My Drive/Jacob_Images/Substrate_Training/B_Substrate/Originals/*.jpg'
for f in glob.glob(file):
    print(f)

Solution

  • Instead of specifying .jpg within the path itself, specify it in glob() function. So, you can try this:

    import glob 
    file = '/content/drive/My Drive/Jacob_Images/Substrate_Training/B_Substrate/Originals'
    for f in glob.glob(file + "/*.jpg"):
        print(f)
    

    Or you can use this code below borrowing code from this post.

    for i in glob.glob('/home/studio-lab-user/sagemaker-studiolab-notebooks/Misc/tsv/**/*.csv', recursive=True):
        print(i)
    

    Your code also works. I am certain the issue is with the path you are providing.

    Using your way:

    Code 1

    Using my way:

    Code 2