简体   繁体   English

Python os.path子文件夹发现

[英]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 我知道我有2种选择:-重复发生(我当前的实现,下面的代码)-在程序开始时生成所有文件夹的列表并调用我的函数

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 ? 另外有人可以帮助我如何(我假设使用os.path库)生成所有文件夹(包括子文件夹)的列表吗?

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: 这是将其添加到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) 因此,如果有人可以:1)告诉我我的态度很好2)提供我代码以生成给定文件夹中所有目录的列表(例如C:\\ users下的所有内容)

Thank you 谢谢

Try os.walk : 尝试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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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