Another example from our Python study group. This is a quick and dirty script to clip all shapefiles in a given directory by another specific shapefile. The output filenames are appended with “_clip” and the script takes care not to clip the clip file by itself.

import glob
import os
import sys
import arcgisscripting

try:
  # a directory path
  workspace = sys.argv[1]

  # a directory for placing outputs
  filetoclipby = sys.argv[2]

except:
  print 'Usage: superclipper.py <workspace> <clipfile>'
  exit()

gp = arcgisscripting.create()
gp.Workspace = workspace
shapefiles = workspace + "*.shp"

for infile in glob.glob(shapefiles):
  # loop through once for each file, 'infile', matching
  # the pattern. 

  if infile == filetoclipby:
    print infile,"is the file to clip by!"
    continue
  else:    
    print infile + " will be clipped by " + filetoclipby
    outfile,extension = os.path.splitext(infile)
    outfile = outfile + "_clip"
    gp.Clip_analysis(infile,filetoclipby,outfile)
import glob
import os
import sys

try:
  # a pattern specified on the command line, like *.txt
  pattern = sys.argv[1]
except:
  print 'Please supply a pattern on the command line.'
  exit()

for infile in glob.glob(pattern):
  # loop through once for each file, 'infile',
  # matching the pattern from the command
  # line. do something with each file.
  # for example, open and print it

  # print the filename
  print infile,'n====='

  # open the file, print it, close it
  filehandle = open(infile)
  for line in filehandle:
    print line.rstrip()
  filehandle.close()

  # print a final newline
  print 'n'

Here’s how it looks when it runs in a directory with two identical files called lipsum.txt and lipsum2.txt:

H:python>myglob.py *.txt
lipsum.txt
=====
"Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit
anim id est laborum."

lipsum2.txt
=====
"Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit
anim id est laborum."