Python仅列出包含特定子文件夹的文件夹

时间:2016-08-30 16:58:12

标签: python python-2.7

我有一个脚本,它将列出所有文件夹和子文件夹并创建一个JSON文件。我想要的只是包含名为" Maps"的子文件夹的文件夹。或"报告"上市。如果它们包含那些,那么只会列出父文件夹,因此"地图","报告"不会显示。目前仍然坚持如何实现这一目标,任何帮助都会很棒。

import os, json, sys
reload(sys)
sys.setdefaultencoding('utf-8')
path = "G:\Testfolders"

def get_list_of_dirs(path):

    try:
        output_dictonary = {}
        list_of_dirs = [os.path.join(path, item) for item in os.listdir(path) if os.path.isdir(os.path.join(path, item )) and os.path.isdir("./Maps") and os.path.isdir("./Reports")]

        output_dictonary["text"] = path.decode('latin1')
        output_dictonary["type"] = "directory"
        output_dictonary["children"] = []
        for dir in list_of_dirs:
        output_dictonary["children"].append(get_list_of_dirs(dir))
        return output_dictonary
    except WindowsError:
        pass

    print json.dumps(get_list_of_dirs(path))

with open(r'U:\JSONDatatest.json', 'w') as f:
     json.dump(get_list_of_dirs(path), f)

编辑:

import os, json, sys

def all_dirs_with_subdirs(path,subdirs):
    # make sure no relative paths are returned, can be omitted
    try:
        output_dictonary = {}

        path = os.path.abspath(path)

        list_of_dirs = []
        for root, dirs, files in os.walk(path):
            if all(subdir in dirs for subdir in subdirs):
                    list_of_dirs.append(root)
        return list_of_dirs
        output_dictonary["text"] = path.decode('latin1')
        output_dictonary["type"] = "directory"

        output_dictonary["children"] = []
        for dir in list_of_dirs:
            output_dictonary["children"].append(all_dirs_with_subdirs(dir))
        return output_dictonary
    except WindowsError:
        pass

with open(r'U:\jsontesting\JSONData.json', 'w') as f:
     json.dump(all_dirs_with_subdirs("G:\TESTPATH", ('Maps', 'Temp')), f)

2 个答案:

答案 0 :(得分:0)

我在想你正在寻找function authentication(user) { return Restangular .all('token') .post('grant_type=password&username=' + user.username + '&password=' + user.password + '&client_id=' + APPLICATION.clientId, undefined, { 'Content-Type': 'application/x-www-form-urlencoded' }); } 命令,我已经在下面使用它实现了一个功能。 (也使它更通用)

os.walk

更新:也是JSON的东西

答案 1 :(得分:0)

如果你想使用glob:

def get_list_of_dirs():

    from glob import glob
    import os.path as path

    # get the directories containing Maps
    maps = set([path.abspath(path.join(f + path.pardir)) 
              for f in glob('**/Maps/')])
    # get the directories containing Reports
    reports = set([path.abspath(path.join(f + path.pardir)) 
                      for f in glob('**/Reports/')])
    # return the common ones
    return maps.intersection(reports)

通过将glob表达式列表传递给函数,然后返回集合的交集或交叉,可以使它更通用。