Monday, October 12, 2009

Listing Only Directories Using Python

Sometimes it's necessary to list directories, but when the os.listdir() method is called, the return list contains both folders and files. To fix this do the following:

dirs = [ name for name in os.listdir(--Directory--)) if os.path.isdir(os.path.join(str(--Directory--), name))]
for d in dirs:
d = str(d)
d = d.upper()
if d.find(".GDB") == -1:
outString = outString + str(d) + "; "

Methods like this are very helpful when you need to use tool validation. It allows you to quickly list all data in a directory, so users can select what they need.

You'll notice that the script has a find(). This is used because file geodatabases are essentially folders and therefore need to be excluded from the generated list.



Michalis Avraam said...

If you are using ESRI's geoprocessor, you can also run the following:

folderList = gp.listworkspaces("*", "Folder")

Of course if you need specific type of datasets, there is ListFeatureclasses, ListRasters, etc.

Andrew said...

That's true, but only folders with shapefiles in them will show then.