Friday, May 6, 2011

Setting paths to data in Python ie the '\'

Python treat the backslash (\) as an escape character.  For example, \n represents a new line, \t is a tab, etc...  When specifying a path, a forward slash (/) can be used in place of a backslash.  Two backslashes can can also be used instead of one to avoid syntax error.  A string literal can also be used by placing the letter r before a string.

Example: Correct way
 

>>> 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: Incorrect Way

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


Enjoy