Browse folders and subfolders python

0

I want to perform a small function to move all files that are ".mp3" to a folder.

For this I have thought to go through all the folders and subfolders in a given direction, and what has occurred to me is the following:

def catch(dir_name):

for item in os.listdir(dir_name):
    print(str(item))
    if item.endswith(".mp3"):
        shutil.move(str(dir_name + "/" + item), "E:/Users/path/destino")
    if os.path.isdir(item):
        print("subcarpeta" + os.path.join('E:','\Users','path',item))
        catch(os.path.join'E:','\Users','path',item))
print("Termino la revision")

Using this, I only do the first pass through the folders, but I do not recursively search the subfolders.

    
asked by Pavl 02.01.2019 в 17:33
source

1 answer

0

you can do it like this:

import os
from pprint import pprint

def sdir(path):
    c=0
    elements={}
    if not os.path.isdir(path) or not os.access(path, os.R_OK):
        raise Exception('pls check path or permits')
    try:
        dirs= os.listdir(path)
    except Exception as e:
        p=path.split("/")
        elements[p[len(p)-2]]="denied access"
        return elements

    for value in dirs:
        if os.path.isdir(path+value):
            pdir=value.replace(path,"").strip("")
            sub=sdir(str(path+value+"/"))
            elements[str(pdir)]=sub
        else:
            elements[c]=str(value)
        c=c+1
    return elements

if __name__ == '__main__':
    pprint(sdir("audio/"))
    
answered by 02.01.2019 в 17:35