Setting workspace relative to script path

advertisement

Absolute & Relative Paths

• Absolute

– Drive + {folder(s)} + {file}

• e.g. C:\Projects\Baffin\Data

– Uniform Naming Convention (UNC) + {folder(s)} + {file}

• \\machine_name\{folder(s)\{file}

• e.g. \\algshare\HOME

• Relative

– No drive or machine_name

– ..\ = one level up, ..\..\ = two levels up, etc

– someFolder = one level down into folder named someFolder

– someFolder\otherFolder = two levels down

– ..\..\Baffin\data = two levels up and two levels down

Paths in Python

Paths to data, scripts, etc. must be in a form Python understands ( r "" , \\, or /) import arcpy arcpy.GetCount_management("c:/temp/streams.shp") arcpy.GetCount_management("c:\\temp\\streams.shp") arcpy.GetCount_management(r"c:\temp\streams.shp")

Relative paths are relative to current working folder

# Current working folder print os.path.abspath(os.path.curdir)

# Path to currently running script print sys.path[0]

# Path to currently running script (more robust) print os.path.dirname(__file__)

2 / 22

Workspace relative to script

Problem:

Relationship between the folder containing your script and the folder containing your data (workspace) is the same but the absolute path to these folders is different.

You want your code to be portable so you don’t want absolute paths in your scripts.

Workspace relative to script

Solution:

Use __file__ and os.chdir to set current working directory to that of the script and then set the workspace relative to it

Download