Skip to Main Content
Banner Image

GIS Workshops: Common Operations

Common Operations

Loop Examples

(All examples print numbers 1 through 5)


numShapes = range(1, 10) # creates a list, 1 to 6
for i in numShapes:
    print i


numShapes = 1

while numShapes < 5

   print numShapes

   numShapes += 1


If Conditional Example

UserSelect = raw_input('(1) Arriving OR (2) Departing\n >> ')
if UserSelect == '1':
    print 'Hello'
elif UserSelect == '2':
    print 'Bye'
else:
    print 'Doh!  Slippery keys, huh?'


List Examples

listShapes = ['fire.shp', 'air.shp', 'water.shp', 'earth.shp']

for item in listShapes:

   print item


listShapes = ['fire.shp', 'air.shp', 'water.shp', 'earth.shp']

for item in listShapes:

   arcpy.buffer(item, item.replace('.shp', '_buffer.shp'), '1.5 Miles')


Error Catching

try:
  arcpy.Select_analysis(input, output)
except:
  arcpy.AddMessage('Uh oh, it appears something has gone awry.')

 


Reading/Writing Text Files

# Opens Text File (r=read, w=write, a=append)

f = open('addresses.csv', 'r')

# Stores each line in a list

listLines = f.readlines()

# Writes to a text file

f.write('I really like the UT Arlington Library!\n')

# Always close files when finished with them

f.close()


def cleanheader(csvtable):
    f=open(csvtable,'r')
    mylist = f.readlines()
    f.close()
    removeitems = [' ', '+', '-', '.', '(', ')', '\'']
    for item in removeitems:
        mylist[0] = mylist[0].replace(item, '')
    f=open(csvtable, 'w')
    for line in mylist:
        f.write(line)
    f.close()


Compile Python Scripts

There are additional modules that can be downloaded to compile Python scripts into executable binaries.

  • Py2Exe
  • PyBuilder
    • Download
    • GUI (graphical user interface) for Py2Exe