简体   繁体   中英

Python os.path subfolder discover

I'm looking for effective way to go to every folder (including subfolder) in my directory list. I then need to run some processes on that folder (like size, number of folders and files etc.).

I know that I have 2 options for that: - Recurrence (my current implementation, code below) - At start of program generating list of all folders and invoking my function in look

I know that my current implementation is not perfect can somebody take a look on it and possibly advise any updates. In addition can somebody help me howto (I'm assuming using os.path library) generate list of all folder including subfolders ?

My current code that analyse folder (using recurrence):

def analyse_folder(path, resultlist=[]):
    # This is trick to check are we in last directory
    subfolders = fsprocess.get_subdirs(path)
    for subfolder in subfolders:
        analyse_folder(subfolder, resultlist)
        files, dirs = fsprocess.get_numbers(subfolder)
        size = fsprocess.get_folder_size(subfolder)

        resultlist = add_result([subfolder, size, files, dirs], resultlist)

    return resultlist

This is the code that getting list of subfolders inside folder:

def get_subdirs(rootpath, ignorelist=[]):
    # We are starting with empty list
    subdirs = []

    # Generate main list
    for path in os.listdir(rootpath):
        # We are only interested in dirs and thins not from ignore list
        if not os.path.isfile(os.path.join(rootpath, path)) and path not in ignorelist:
            subdirs.append(os.path.join(rootpath, path))

    # We are giving back list of subdirectories
    return subdirs

And this is simple function to add it to resullist:

def add_result(result, main_list):
    main_list.append(result)
    return main_list

So if anyone can: 1) Tell me is my attitude is good 2) Provide me code to generate list of all of directories in given folder (for example everything under C:\\users)

Thank you

Try os.walk :

import os

for (root, dirs, files) in os.walk(somefolder):
    # root is the place you're listing
    # dirs is a list of directories directly under root
    # files is a list of files directly under root

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM