Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading