Python List Shapefiles

16508
6
04-20-2010 10:25 PM
DaveMarkey
New Contributor III
Hi.

I am trying to list datasets within a directory.  I have played with ListDatasets and ListFeatureClasses.  These work successfully with geodatabase and CAD layers.  How do I construct a Python script that lists shapefiles?

Thanks,

Dave.
6 Replies
DavidWynne
Esri Contributor
I am trying to list datasets within a directory.  I have played with ListDatasets and ListFeatureClasses.  These work successfully with geodatabase and CAD layers.  How do I construct a Python script that lists shapefiles?


Hi Dave,
ListFeatureClasses should do the trick.  Are you doing something like this below?

import arcpy

# Set workspace environment to a folder
arcpy.env.workspace = "c:/temp" 

# A list of shapefiles
arcpy.ListFeatureClasses() 


-Dave
RDHarles
Occasional Contributor
I do it like this:

import os

ws = "c:/temp"

for file in os.listdir(ws):    
    if file.endswith(".shp"):
        print file
DaveMarkey
New Contributor III
Hi.

Thanks for the responses.  Prior to my post I tried the 'listdatasets' and 'listfeatureclasses' but unfortunatlely they do not list shapefiles.  This is to be expected from the listfeatureclasses as shapefiles do not exist in a geodatabase file.  The listdatasets only lists TIN, Rasters and CAD files, even when the ALL option is specified (please refer to 'List Datasets Methods' in the desktop help).

Fortunately I have found the 'ends with' reply works as desired and appears to be more flexible as could be used for any file type.  Could this script be expanded to list multiple file types?

Thanks

Dave.
DarshaHardy
New Contributor II
There was a bug with the ListFeatureClasses method (introduced by a particular service pack) in 9.2

See here this thread in the old forums http://forums.esri.com/Thread.asp?c=93&f=1729&t=240535
RDHarles
Occasional Contributor
  Could this script be expanded to list multiple file types?.


Sure.

List all files that end with .shp or .dxf or start with 'str':

import os

ws = "c:/temp"

for file in os.listdir(ws):    
    if file.endswith(".shp") or file.endswith(".dxf") or file.startswith("str"):
        print file



You can also use wildcards like this:

import os, glob
# Delete all files that contain the word 'points'
for file in glob.glob("*points*"):
    os.remove(file)
DaveMarkey
New Contributor III
Thanks people.  Some good ideas here.  I am wanting to learn Python from an ArcGIS perspective.  Where is some good learning material that teaches Python for ArcGIS?  I have downloaded the documentation from Python website but is only good for learning from scratch.

Also, thanks for the heads up on the ListFeatureClasses bug.  Appears this should work with shapefiles but doesn't due to a service pack.  For those of us managing and developing ArcPad, this could be a real problem as ArcPad mostly only works with shapefiles.

Dave.