Home > Software design >  Is it possible to loop all the elements of the list at once
Is it possible to loop all the elements of the list at once

Time:09-23

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
 }

CodePudding user response:

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']}

CodePudding user response:

How about doing it like this:-

import glob

D = {}
for _r in glob.glob('/home/work/assignments/chapters/*/*'):
    t = _r.split('/')
    if (d := t[-2]) in D:
        D[d].append(t[-1])
    else:
        D[d] = [t[-1]]
print(D)

CodePudding user response:

Try this one

import os
def list_files(dir):
    for root, dirs, files in os.walk(dir):
        names=[]
        for name in files:
            print(name)
            r.append(os.path.join(root, name))
            names.append(os.path.join(root, name))
        output[root.split('/')[-1]]=names
    return output

CodePudding user response:

How about an "one-liner" like this one?

from os import sep
from glob import glob
from pprint import pprint

pprint({d.split(sep)[1] : [f for f in  glob(d  '/*.*')] for d in glob('/home/work/assignments/chapters/*/')})

sep for cross-platform support, pprint to "pretty-print", d for directory and f for folder.

  • Related