Search code examples
pythonpathfilepath

Storing the path to folders and inner folders


i'm having difficulties trying to read from sub-folders that are inside a folder. What im trying to do is: i have my path "C:\Dataset" which has 2 folders inside them and inside both folders, i have person names that have pictures for example: "C:\Dataset\Drunk\JohnDoe\Pic1", "C:\Dataset\Sober\JaneDoe\Pic1". I want to be able to read each picture and store them in a path variable.

At the moment, what i got so far, basically, i get the images as long as they are inside Drunk and Sober only, for instance: 'C:\Dataset\Drunk\Pic1', and the code that i am using to do is this:

DATADIR = "C:\Dataset"
CATEGORIES = ["Positive", "Negative"]

for category in CATEGORIES:
    path = os.path.join(DATADIR, category)
    for img in os.listdir(path):
        img_path = os.path.join(path,img)
        img_data = open(img_path, 'r').read()
        break
    break

Basically, what i am trying to do is that when i iterate inside Drunk folder it also iterates inside the inner folders, reading the path to the pictures that are in C:\Dataset\Drunk\JohnDoe\nthPic, C:\Dataset\Drunk\JoeDoe\nthPic, C:\Dataset\Drunk and Sober \nthJoe\nthPic C:\Dataset\Drunk\JamesDoe\nthPic. Therefore, when I do the reading, it grabs the whole folder map

This is basically what my goal is.


Solution

  • You need one nesting more: It saves all images in the dictionary images, key is the full path.

    DATADIR = "C:\Dataset"
    CATEGORIES = ["Drunk", "Sober"]
    
    images = {}
    
    for category in CATEGORIES:
        path = os.path.join(DATADIR, category)
        for person in os.listdir(path):
            personfolder = os.path.join(path, person):
            for imgname in os.listdir(personfolder):
                fullpath = os.path.join(personfolder, imgname)
                images[fullpath] = open(fullpath, 'r').read()