Setting paths to data in Python

Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab. When specifying a path, a forward slash (/) can be used in place of a backslash. Two backslashes can be used instead of one to avoid a syntax error. A string literal can also be used by placing the letter r before a string containing a backslash so it is interpreted correctly.

Example 1: Valid use of paths in Python

import arcpy

arcpy.GetCount_management("c:/temp/streams.shp")
arcpy.GetCount_management("c:\\temp\\streams.shp")
arcpy.GetCount_management(r"c:\temp\streams.shp")

Example 2: Invalid use of paths in Python

In the following sample, backslashes are used by mistake, and \t is interpreted as a tab by Python. GetCount will fail, as the path is interpreted differently than it was intended.

import arcpy
arcpy.GetCount_management("c:\temp\streams.shp")

# ExecuteError: Failed to execute. Parameters are not valid.
# ERROR 000732: Input Rows: Dataset c:      em\streams.shp does not exist or is not supported
# Failed to execute (GetCount)
TipTip:

It is possible to have a feature class and a feature dataset with the same name contained within a geodatabase. In such a case, the feature class and feature dataset will have the same ArcCatalog path. Most tools work with one or the other. However, for those tools that can work with either, such as the Copy tool, the data type can be specified to avoid ambiguity.

Related Topics


12/15/2011