Python - 选择包含特定字符串的目录

Python - Choose directory that contains a specific string

以下代码打印目录列表,这些目录恰好包含一个 3 字母代码,示例:

//Server/Jobs/2016\AAM - 'areallylongfilename'/

//Server/Jobs/2016\CLM - 'areallylongfilename'/

//Server/Jobs/2016\COO - 'areallylongfilename'/

import os
basepath = '//Server/Jobs/2016'
for fname in os.listdir(basepath):
    path = os.path.join(basepath, fname)
    if os.path.isdir(path):
        print(path)

如何根据3个字母代码从列表中获取一个目录?

import os
basepath = '//Server/Jobs/2016'
asked_name = 'COO'
if len(asked_name) != 3:
        print "Expected 3 letter code, got:", asked_name
else:
        for fname in os.listdir(basepath):
                path = os.path.join(basepath, fname)
                if os.path.isdir(path):
                        if fname == asked_name:
                                print(path)

假设要扫描"d:"盘,可以编码为:

import os
dir="d:\"
for root,dirs,files in os.walk(dir):
    for a_dir in dirs:
        if ("Server" in a_dir) and ("Jobs" in a_dir) and ("2016" in a_dir):
            print os.path.join(root,a_dir)