Storing the path to folders and inner folders

Question:

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:DatasetDrunkJohnDoePic1", "C:DatasetSoberJaneDoePic1". 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:DatasetDrunkPic1', 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:DatasetDrunkJohnDoenthPic, C:DatasetDrunkJoeDoenthPic, C:DatasetDrunk and Sober nthJoenthPic C:DatasetDrunkJamesDoenthPic. Therefore, when I do the reading, it grabs the whole folder map

This is basically what my goal is.

Asked By: user11597888

||

Answers:

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()
Answered By: bb1950328
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.