Ryan White Ryan White - 29 days ago 12
Python Question

Python - Choose directory that contains a specific string

The following code prints a list of directories that all happen to contain a 3 letter code, Example:

//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)


How can I get one directory from the list based on the 3 letter code?

Answer
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)
Comments