banany12
banany12

Reputation: 1

Getting files from subfolder

I'm pretty new to python, so please bear with me. I'm trying to write a code that utilizes face-recognition, and with that i need to be able to access subfolders.

Currently i'm having issues with finding the folder "images". When executing the code, i'm in the folder face-recognition and need to access images that is one level under.

- root

--- face-recognition

-- images

def getImagePath():
    currentPath = os.path.dirname(__file__) # Absolute dir the script is in
    filepath = "../images/" # The path where the pictures are uploaded
    fileList = os.listdir(os.path.join(currentPath, filepath))
    return fileList;

Executing this code gives error `FileNotFoundError: [Errror 2] No such file or directory: '../images/'

Edit: After trying to rewrite the code i saw what the actual problem is:

def getImages():
    currentPath = os.path.dirname(os.path.abspath(__file__)); # Absolute dir the script is in
    filepath = "../images/"; # The path where the pictures are uploaded
    directory = os.listdir(os.path.join(currentPath, filepath));
    images = [ fi for fi in directory if fi.endswith(('.JPG', '.jpg', 'jpeg', '.JPEG')) ];
    return images;

Running this code snippet trough the terminal on my mac works with no errors. But running the same code on the raspberry-pi 3, the error is thrown, and it does not make sens.

Solution: While checking the images folder i found that i have a .gitkeep and .gitignore that ignores all files, (even .gitkeep), and that's why it threw an error because it removed the folder when cloning the repo on the raspberry pi.

Upvotes: 0

Views: 335

Answers (2)

wwii
wwii

Reputation: 23753

C:\root
├───my
│   └───path
│       └───tmp.py
├───image

The Pathlib module is handy (Python version 3.4+). For the directory structure above...

In tmp.py:

from pathlib import Path
p = Path(__file__).parent

The image directory is under the parent of tmp.py's parent.

>>> print(p)
C:\root\my\path
>>> print(p.parent.parent)
C:\root
>>> image_path = p.parent.parent / 'image'
>>> for img in image_path.iterdir():
...     print(img)

C:\root\image\empty.gif
C:\root\image\o.gif
C:\root\image\x.gif
>>>
>>> [str(img) for img in image_path.iterdir()]
['C:\\root\\image\\empty.gif', 'C:\\root\\image\\o.gif', 'C:\\root\\image\\x.gif']
>>>

Upvotes: 1

Dan Steingart
Dan Steingart

Reputation: 775

Two parts to this:

1) You're going the wrong way. ../images/ goes up one directory. You just want images/. For absolute referencing you want /face-recognition/images

2) glob is your friend here https://docs.python.org/3/library/glob.html

import glob 
file_list = glob.glob('/face-recognition/images/*.png')

or whatever extension you need.

Upvotes: 1

Related Questions