This first example script reports the spatial reference (coordinate system) of a feature class stored in a geodatabase:
# Opens a feature class from a geodatabase and prints the spatial reference import arcpy featureClass = "C:/Data/USA/USA.gdb/StateBoundaries" # Describe the feature class and get its spatial reference desc = arcpy.Describe(featureClass) spatialRef = desc.spatialReference # Print the spatial reference name print spatialRef.Name
This may look intimidating at first, so let’s go through what’s happening in this script, line by line. Watch this video to get a visual walkthrough of the code. You'll notice a typo in the video / screenshot below desc.SpatialReference should be desc.spatialReference - as per the documentation.
Again, notice that:
- A comment begins the script to explain what’s going to happen.
- Case sensitivity is applied in the code. "import" is all lower-case. So is "print". The module name "arcpy" is always referred to as "arcpy," not "ARCPY" or "Arcpy". Similarly, "Describe" is capitalized in arcpy.Describe.
- The variable names featureClass, desc, and spatialRef that the programmer assigned are short, but intuitive. By looking at the variable name, you can quickly guess what it represents.
- The script creates objects and uses a combination of properties and methods on those objects to get the job done. That’s how object-oriented programming works.
Trying the example for yourself
The best way to get familiar with a new programming language is to look at example code and practice with it yourself. See if you can modify the script above to report the spatial reference of a feature class on your computer. In my example the feature class is in a file geodatabase; you’ll need to modify the structure of the featureClass path if you are using a shapefile (for example, you'll put .shp at the end of the file name, and you won't have .gdb in your path).
Follow this pattern to try the example:
- Open PythonWin and click File > New.
- Choose to make a Python script and click OK.
- Paste in the code above and modify it to fit your data (change the path).
- Save your script as a .py file.
- Click the Run button to run the script. Make sure the Interactive Window is visible when you do this, because this is where you’ll see the output from the print keyword. The print keyword does not actually cause a hard copy to be printed!
We'll take a short break and do some reading from another source. If you are new to Python scripting it can be helpful to see the concepts from another point of view.
- Chapter 4 deals with the fundamentals of Python. We will need a few of these to get started and we'll revisit this chapter in Lesson 2. For now read sections 4.1-4.7 revising what we read in 4.5 earlier.
- Chapter 5 talks about working with arcpy and functions - read sections 5.1-5.6.