clip analysis in arcpy - arcpy

I have one shapefile that covers an entire city, and a list of shapefiles which are buffers in different places in the city. I want to clip the city with each buffer. I tried using ArcPy in Python but the code is not working. What am I doing wrong?
import arcpy
from arcpy import env
from import *
env.workspace = "U:\Park and Residential Area\Test\SBA park_res_buffer_5\SBA.gdb"
infeature= "U:\Park and Residential Area\Test\park_res_merge.shp"
clipfeatture = arcpy.ListFeatureClasses("*", "polygon")
for i in clipfeatture:
outclipfeatture = arcpy.Clip_analysis(infeature,i)"U:\Park and Residential Area\Test\SBA park_res_buffer_5/"*i)

This is the appropriate syntax for using Clip in ArcPy:
arcpy.Clip_analysis(in_features, clip_features, out_feature_class)
so your for loop should instead be something like:
for i in clipfeatture:
outfeature = "U:\Foo\Bar\" + i
arcpy.Clip_analysis(infeature, i, outfeature)

I would also print() each file path string so you can check that its syntax is being used appropriately. Backslashes are escape characters in Python and can have special properties when followed by key letters.
I always put an r in front of any string that contains a file path, e.g. r"\\srvr\drv\proj\gdb.gdb\fc"; this tells Python it is a raw string and ignores the escape functions.
See link below for an entertaining analogy on handling backslashes in filenames.

To do multiple clip with more than one clip features, you have to first create a list of all clip features and iterate them.
import arcpy
arcpy.env.workspace = file_path
fcList = arcpy.ListFeatureClasses()
for fc in fcList:
arcpy.Clip_analysis(input_feature, fc, output_feature)
Be sure to have different names for your multiple outpus. You can use arcpy.CreateUniqueName() to create distinct names such as Buffer.shp, Buffer_1.shp, Buffer_2.shp ...

You can also export the iterate feature selection tool from Model Builder if each place is unique.
# Import arcpy module
import arcpy
# Load required toolboxes
arcpy.ImportToolbox("Model Functions")
# Local variables:
Selected_Features = ""
Value = "1"
# Process: Iterate Feature Selection
arcpy.IterateFeatureSelection_mb("inputfeature", "fields", "false")


Chronic (Ruby NLP date/time parser) for python?

Does anyone know of a library like chronic but for python?
Have you tried parsedatetime?
You can try Stanford NLP's SUTime. Related Python bindings are here:
Make sure that all the Java dependencies are installed.
I was talking to Stephen Russett at chronic. I came up with a Python example after he suggested tokenization.
Here is the Python example. You run the output into chronic.
import nltk
import MySQLdb
import time
import string
import re
sentence = 'Available June 9 -- August first week'
tokens = nltk.word_tokenize(sentence)
parts_of_speech = nltk.pos_tag(tokens)
print parts_of_speech
#allow white list
white_list = ['first']
#allow only prepositions
approved_prepositions = ['NNP', 'CD']
filtered = []
for word in parts_of_speech:
if any(x in word[1] for x in approved_prepositions):
elif any(x in word[0] for x in white_list):
#if word in white list, append it
print filtered
#normalize to alphanumeric only
normalized = re.sub(r'\s\W+', ' ', ' '.join(filtered))
print filtered

Batch clipping multiple rasters with a single shapefile using arcpy

import arcpy, glob, os
from arcpy import env
from import *
# Set the input workspace
arcpy.env.workspace = r"F:\madhavi\images_to_clip"
# Absolute path to your mask layer
mask = "F:\madhavi\shapefile\shp_gang_only_final.shp"
# Copying all the input rasters in an array
rasters = arcpy.ListRasters()
# Loop through rasters, append names and save files
for raster in rasters:
output_raster = raster.replace(".TIF", "_clip.TIF")
rasterObject =, mask, output_raster)"F:\madhavi\clipped_images")
There are two problems that I am encountering with this Python script and they are as follows:
Firstly, the script is clipping only the first raster in the folder: F:\madhavi\images_to_clip and not for all the rasters in that folder. Therefore, the for loop is not working properly.
By the way, the folder on which the for loop is working contains only two .TIF images.
Secondly, the script is not saving the outputs in the desired folder.
I am still getting "Parsing Error SyntaxError: EOL while scanning string literal (line 18)". Therefore, there is a problem in "output_raster = raster.replace(".TIF", "_clip.TIF")".
I think the problem is in this variable assignment:
mask = "F:\madhavi\shapefile\shp_gang_only_final.shp"
The error message is complaining about string literal -- so try instead ensuring it is a string literal:
mask = r"F:\madhavi\shapefile\shp_gang_only_final.shp"

How to organize data from a .DXF file

I need to take apart a GDS file to do more detailed analysis on it.
In particular I need to count the numbers of design layers, the number of polylines in each layer and the vertices of each of the polyline for a design.
My trouble is creating class(s) with all that information. In the end I would like to be able to get the data for each vertex by specifying something like
Lyr[5].pl[3].vertx[7] Where 5 is the fifth layer, 3 is the third polyline in that layer and 7 is the seventh vertex on that polyline.
I can get the layers and polylines fine but can't get my mind around how to start adding the vertices.
BTW, I am not working directly with a GDS file but a format called .DXF which is
a simple single string per line text file.
Here is my code so far.
import sys #see sys modules using goggle
import string
import math
class layer:
def __init__(self,layer):
def add_pline(self,y):
def add_nplines(self):
class vertx
def __init__(self,n): ## Running out of ideas here
def main():
## Get the layers
while 1:
if "CONTINUOUS" in s :
s=inFile.readline() #burn one line in DXF file
s=inFile.readline() #name of the layer
lyr[nlayers]=layer(s) # save the layer
if 'POLYLINE' in s: break
## Get the polylines
while 1:
if 'POLYLINE' in s:
s=inFile.readline() #burn a line
s=inFile.readline() #layer name
for i in range(0,nlayers+1):
if s==lyr[i].layer:
if 'EOF' in s: break
for i in range(0,nlayers+1):
print i,'Layer=',lyr[i].layer,' no plines= ',lyr[i].nplines
You can use my ezdxf package to handle DXF files. It is available on PyPI
import ezdxf
dwg = ezdxf.readfile("your.dxf")
msp = dwg.modelspace() # contains all drawing entities
polylines = msp.query("POLYLINE") # get all polylines in modelspace
for polyline in polylines:
layer = polyline.dxf.layer # layername as string
points = polyline.points() # all vertices as (x, y [,z]) tuples
# for more see
ezdxf handles all DXF versions and can also append data to existing DXF files or create new DXF files.

How to format an Address for multiline display?

Similar to this question from 2011, which lacks a satisfactory answer:
An app that I'm working on will be deployed internationally. The app itself only cares about the lat/long of an Address, but it will need to display the Address to the user in a multi-line format. Google's geocoder provides a formatted address, but it's on a single line separated by commas. Splitting this into lines would require knowledge of how multiline addresses are formatted in a given country. In the US, for example, it's customary to place the city and state on the same line, separated by a comma.
Is there a built-in method (or third-party library or Web service) that will format a multi-line address from an Address, taking into account that reverse-geocoded addresses may be incomplete?
Check out googlei18n/libaddressinput: Google’s postal address library, powering Android and Chromium. There are two modules in the project :android and :common. You should only need :common to format the address for multi-line display.
import android.location.Address;
import android.text.TextUtils;
public static String getFormattedAddress(#NonNull final Address address,
#NonNull final String regionCode) {
final FormatInterpreter formatInterpreter
= new FormatInterpreter(new FormOptions().createSnapshot());
final AddressData addressData = (new AddressData.Builder()
.setCountry(regionCode) // REQUIRED
// Fetch the address lines using getEnvelopeAddress,
List<String> addressFragments = formatInterpreter.getEnvelopeAddress(addressData);
// join them, and send them to the thread.
return TextUtils.join(System.getProperty("line.separator"),
NOTE: regionCode must be a valid iso2 country code, because this is where the format interpreter pulls the address format from. (See RegionDataConstants for the list of formats, if you're curious.)
Sets the 2-letter CLDR region code of the address; see
AddressData#getPostalCountry(). Unlike other values passed to the
builder, the region code can never be null.
Example: US
ST. LOUIS, MO 63101
Example: JP

Insert file (foo.txt) into open file (bar.txt) at caret position

What would be the best method, please, to insert file (foo.txt) into open file (bar.txt) at caret position?
It would be nice to have an open-file dialog to choose anything to be inserted.
The word processing equivalent would be "insert file" here.
Here is a substitute for foo.sublime-snippet, which can be linked to form files elsewhere:
import sublime, sublime_plugin
class InsertFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
v = self.view
template = open('foo.txt').read()
print template
v.run_command("insert_snippet", {"contents": template})
From within a text command you can access the current view. You can get the cursor positions using self.view.sel(). I don't know how to do gui stuff in python, but you can do file selection using the quick panel (similar to FuzzyFileNav).
Here is my unofficial modification of which permits me to insert-a-file-here using the quick panel. It works on an OSX operating system (running Mountain Lion).
The only disadvantage I see so far is the inability to translate a double-slash \\ in the form file correctly -- it gets inserted instead as just a single-slash \. In my LaTex form files, the double-slash \\ represents a line ending, or a new line if preceded by a ~. The workaround is to insert an extra slash at each occurrence in the actual form file (i.e., put three slashes, with the understanding that only two slashes will be inserted when running the plugin). The form files need to be LF endings and I'm using UTF-8 encoding -- CR endings are not translated properly. With a slight modification, it is also possible to have multiple form file directories and/or file types.
import sublime, sublime_plugin
import os
class InsertFileCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.show_quick_panel(self.templates, self.template_selected)
def find_templates(self):
self.templates = []
self.template_paths = []
for root, dirnames, filenames in os.walk('/path_to_forms_directory'):
for filename in filenames:
if filename.endswith(".tex"): # extension of form files
self.template_paths.append(os.path.join(root, filename))
self.templates.append(os.path.basename(root) + ": " + os.path.splitext(filename)[0])
def template_selected(self, selected_index):
if selected_index != -1:
self.template_path = self.template_paths[selected_index]
print "\n" * 25
print "----------------------------------------------------------------------------------------\n"
print ("Inserting File: " + self.template_path + "\n")
print "----------------------------------------------------------------------------------------\n"
template = open(self.template_path).read()
print template
view = self.window.run_command("insert_snippet", {'contents': template})
sublime.status_message("Inserted File: %s" % self.template_path)