Is it possible to loop all the elements of the list at once

Issue

Wanted to read folder contents and convert it as a dictionary.. My rudimentary approach below.

Code snippet:

import os

    b_path = "/home/work/assignments/chapters"
    output = {}
    
    for path, subdirs, files in os.walk(b_path):
        for name in subdirs:
            tmp = os.path.join(path, name)
            tmp_arr = [i for i in os.listdir(tmp)]
            for i, v in enemurate(tmp_arr):
                output[name] = [os.path.join(tmp, v)]
                output[name].append(os.path.join(tmp, <not sure how to achieve this> ))]
    print(output)

subdirs prints folder names – countries, social, algebra, functions etc..

subdir (folder) contains 2 files under it, 1. yaml file, 2. zip or tar.gz file.

tmp_arr's output

['func.yaml', 'sensor.zip']
['packets.tar.gz', 'check.yaml']
['mt101.tar.gz', 'provider.yaml']
and so on.

I wanted my dictionary to look like:

{
    "countries": [
        "/home/work/assignments/chapters/countries/func.yaml",
        "/home/work/assignments/chapters/countries/sensor.zip"
    ],
    "social": [
        "/home/work/assignments/chapters/social/check.yaml",
        "/home/work/assignments/chapters/social/packets.tar.gz"
    ],
     and so on
 }

Solution

I had a folder structure like this :

Sample
│
└───folderA
│   │   A1.txt
│   │   A2.txt
│  
└───folderB
    │   B1.txt
    │   B2.txt

Code

import os

b_path = "Sample"
output = {}

for path, subdirs, files in os.walk(b_path):
    for name in files:
        folder = os.path.basename(path)
        if output.get(folder) is None:
            output[folder] = [name]
        else:
            output[folder].append(name)

print(output)

Output

{'folderA': ['A1.txt', 'A2.txt'], 'folderB': ['B1.txt', 'B2.txt']}

Answered By – vnk

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published