6

In ArcGIS modelbuilder I want to check if a shapefiles exists, if not I want to create the shapefile in that folder. I guess the calculate value tool within ArcGIS modelbuilder can be used, but I need some python scripting to do the work.

Any idea or python script examples?

8

I think you want the arcpy.Exists function:

>>> import arcpy
>>> arcpy.env.workspace = r"D:\temp"
>>> if arcpy.Exists("Cameron.shp"):
...     print "Exists"
...
Exists
>>>
3

@Chad Chopper is right. You can also use ValidateTableName() function which can determine whether a specific name is valid and unique to a specific workspace.

The Exists() function can check to see whether the table name is unique for a given workspace.

The difference between ValidateTableName() and Exists() is that The ValidateTableName() function does not determine that the specified name is unique to the specified workspace. It only returns a valid table name for that workspace.

Example Code:

# Move all shapefiles from a folder into a geodatabase
#
import arcpy
from arcpy import env

# Set the workspace. List all of the shapefiles
#
env.workspace = "D:/St_Johns"
fcs = arcpy.ListFeatureClasses("*")

# Set the workspace to SDE for ValidateTableName
#
env.workspace = "Database Connections/Bluestar.sde"

# For each feature class name
#
for fc in fcs: 
    # Validate the output name so it is valid
    #
    outfc = arcpy.ValidateTableName(fc)

    # Copy the features from the workspace to a geodatabase
    #
    arcpy.CopyFeatures_management(fc, outfc)

you can get more info here...

0

For a pure python solution, you can use os.path.isfile to check if the shapefile exists and is indeed a file.

import os

myfile = r'C:\temp\myshp.shp'

if os.path.isfile(myfile):
    print "The file exists"
    # Do something

Not the answer you're looking for? Browse other questions tagged or ask your own question.