1

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)

1 Answers1

0

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

  • I just tried your answer and it still doesn't work – Chidera Chukwumah Mar 10 '22 at 11:36
  • Please check if you typed the path correctly. Use `pwd` to check the path and then try. For me, the code is working perfectly, though I have different directories and files within it. –  Mar 10 '22 at 11:40
  • I checked pwd and it came up with: /content/drive/MyDrive/Jacob_Images – Chidera Chukwumah Mar 10 '22 at 12:01
  • Only this path? What about the `/Substrate_Training/B_Substrate/Originals` part? –  Mar 10 '22 at 12:05
  • I am having trouble changing the path to /Substrate_Training/B_Substrate/Originals - it wont seem to allow me to – Chidera Chukwumah Mar 10 '22 at 12:10
  • Try [this](https://stackoverflow.com/questions/1810743/how-to-set-the-current-working-directory) to get to know about your path and change the directory accordingly. –  Mar 10 '22 at 12:12
  • import os os.chdir('/content/drive/MyDrive/Jacob_Images/Substrate_Training/B_Substrate/Originals') - however it says FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/MyDrive/Jacob_Images/Substrate_Training/B_Substrate/Originals' – Chidera Chukwumah Mar 10 '22 at 12:15
  • 1
    Then please first check how to specify paths while using Python. Also check where your code file is present (in what directory). Then specify the path and run the code. Because the issue here is with the path and not with your code. –  Mar 10 '22 at 12:25