Obtaining the number of files based on the extension and folder you give it in the function

Viewed 26

I want to design a function as follows:

 explore("jpg", "../test_media")

outputsample:

{'../test_media':1,'../test_media/travel_photos':3}

That is, the output of the function should be a dictionary where each key is the address of a folder and each value is the number of files with that extension directly in that folder. If a folder does not contain the file we want, it should not be in the dictionary.

The code I wrote myself:

import os


def explore(ttype, address):
    
    list_dir = list(os.walk(address))
    directoirs = dict()
    for x in list_dir:
        count = 0
        if x[2]:
            for y in x[2]:
                t = y.split('.')
                if t[1].lower() == ttype:
                    count += 1
        if count:
            directoirs[str(x[0])] = count

    return directoirs

But it does not give the desired output

1 Answers

you can edit function like this : import os

def explore(extension, addr):
    result = dict()
    for obj in os.walk(addr):
        for name in obj[2]:
            if "." in name and name.split('.')[-1].lower() == extension.lower():
                try:
                    result[obj[0]] += 1
                except KeyError:
                    result[obj[0]] = 1
    return result

sample output:

   >>> explore("jpg", "../test_media")
{'../test_media':1,'../test_media/travel_photos':3}
>>> explore("txt", "../test_media/travel_photos")
{'../test_media/travel_photos':1}
>>> explore("mkv", "../test_media/")
{}

 Directory
     ├── source
        │     └──Explorer.py
        │
        test_media
        ├── IMG_2235.jpg
        ├── travel_photos
        │   ├── 2018-11-09_11-27-14.3gP
        │   ├── IMG_20171017_052418.jpg
        │   ├── 20180311_214539.JPG
        │   ├── IMG_2237.jpg   
        │   └── note.tXt
        └── vid1
            ├── images
            │   └── JPG
            └── VID_20170425_184731.mp4
  
Related