1

I have a program that selects certain files and imports them to the Table Of Contents in ArcMap.

I would like to do some self intersect operations to all and put them both the original files and the intersected to a geodatabase.

Code attempt:

The below works the part after importing them to the Table Of Contents. Can you help make the code functional?

for files in TOC: #somehow store all files located in Table Of Contents to a variable.
    arcpy.Intersect_analysis([[i, i],i + '_inte')#add the '_inte' to the output 
    #and here move to the geodatabase both the original files and the intersected ones

My code to import to TOC:

arcpy.env.workspace = r"C:\Users\user\Desktop\20181018_CHECKS\05052"

walk = arcpy.da.Walk(datatype="FeatureClass")

for dir_path, dir_names, file_names in walk:
    for filename in file_names:
        if filename.endswith('.shp'):
            print(filename)

walk = arcpy.da.Walk(datatype="FeatureClass")
for dir_path, dir_names, file_names in walk:
    for filename in file_names:
        if filename.endswith('.shp'):
            arcpy.env.addOutputsToMap = True                
            arcpy.env.overwriteOutput = True                            
            arcpy.MakeFeatureLayer_management(os.path.join(dir_path, filename),filename)

What is there now should be self-intersected and copied to the the geodatabase with the original files too.

  • You want to intersect for ex. roads layer with itself? – JuniorPythonNewbie Oct 23 '18 at 14:15
  • That is correct.But the question is how to move all of these files to a geodatabase. – user130347 Oct 23 '18 at 14:23
  • Moving new ones to the gdb is easy. Original ones I think is pretty straight forward. I can write some code later if you want. Files in TOC are not in the 'air' you can check their source in properties. With that info we can work something out. – JuniorPythonNewbie Oct 23 '18 at 14:25
  • That would be very helpful. – user130347 Oct 23 '18 at 14:29
  • 2
    Since you already coded adding to TOC, you should already have the names/paths of the feature classes. Please edit your question to include this code to make it easier for us to make suggestions that go with your existing process. The tool I'd use is arcpy.FeatureClassToGeodatabase_conversion – smiller Oct 23 '18 at 14:34
1

EDIT

I hope this gonna work for you. Add your gdb location. Give it a try a tell me results.

import arcpy
arcpy.env.overwriteOutput = True
arcpy.env.workspace = r"C:\Users\user\Desktop\20181018_CHECKS\05052"
arcpy.env.addOutputsToMap = True
gdb = r"**GDBADRESS**"

fc_list =  arcpy.ListFeatureClasses()

for fc in fc_list:
    print (fc)
    file_name = fc.split('.')[0]
    arcpy.FeatureClassToGeodatabase_conversion(fc, gdb)
    in_fc = [fc, fc]
    arcpy.Intersect_analysis(in_fc,('{0}\{1}_inte'.format(gdb,file_name))

Tool for this: I am aware that this is code is like using a sledgehammer to crack a nut, but it was the easiest solution for me to help OP.

It is working, I don't see point of doing intersections of fls, but code is working as follows:

1) You pick feature layers from TOC

2) You select target gdb

3) Tool copies feature layer to gdb and then save intersected fls to the gdb


To use this tool save following code to the *.pyt extension and put it to the folder which you have connected in your catalog pane.

I tested it with ArcGIS Pro 2.2.3, hope it is gonna work with ArcMap.

If you need any additional help with using this, feel free to comment.

import arcpy

class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "UserCustomTool"
        self.alias = ""

        # List of tool classes associated with this toolbox
        self.tools = [Tool_for_user]


class Tool_for_user(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Tool for user"
        self.description = "By JuniorPythonNewbie for GIS stack exchange "
        self.canRunInBackground = False


    def getParameterInfo(self):
        """Define parameter definitions"""
                # Pierwszy parametr
        in_layers = arcpy.Parameter(
            displayName = "Put all the layers from TOC",
            name = "in_fl",
            datatype = "GPFeatureLayer",
            parameterType = "Required",
            direction = "Input",
            multiValue = True)
        out_gdb = arcpy.Parameter(
            displayName = "Select gdb where all stuff gonna be saved",
            name = "out_gdb",
            datatype = "DEWorkspace",
            parameterType = "Required",
            direction = "Input")

        p =[in_layers, out_gdb]
        return p

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""


    def execute(self, parameters, messages):
        gdb = parameters[1].valueAsText
        arcpy.env.overwriteOutput = True
        chosen_fl = parameters[0].valueAsText.split(',')
        for fl in chosen_fl:
            arcpy.FeatureClassToGeodatabase_conversion(fl, gdb)
            in_fl = [fl, fl]
            arcpy.Intersect_analysis(in_fl, ('{0}\{1}_inte'.format(gdb,fl))
        return
  • This is too much indeed, I have added my code that imports to the TOC in my question if you want to suggest something else. Thank you very much for the effort though. – user130347 Oct 24 '18 at 7:59
  • Will you be pleased if code would do something like: 1) import all shps from given dir to gdb 2) perform intersection inside gdb? but without whole adding to TOC? – JuniorPythonNewbie Oct 24 '18 at 8:18
  • Yes. Just a thought before you consider this though. If we add a line after MakeFeatureLayer_management from my code -last line, that copies each one in a loop to the gdb and also does the intersect maybe if it could work we would solve it with only two extra lines of code. The thing is that I don't know what function could do this. – user130347 Oct 24 '18 at 8:33
  • edited, im not sure about part about adding it to TOC – JuniorPythonNewbie Oct 24 '18 at 8:34
  • Just adding the FeatureClassToGeodatabase_conversion and intersect did the trick.Thank you very much. I need some clarifications: Does FeatureClassToGeodatabase_conversion takes from the env. files and adds them to the gdb? – user130347 Oct 24 '18 at 8:53
0

Based on your earlier code, I added (within the same loop that adds the original shapefile to the map) intersection with self, outputting to a geodatabase, and then FeatureClassToGeodatabase_conversion to import the original shapefile to the same geodatabase.

import os 
import arcpy
arcpy.env.overwriteOutput = True
arcpy.env.workspace = r"C:\Users\user\Desktop\20181018_CHECKS\05052"
arcpy.env.addOutputsToMap = True
gdb = r"**GDBADRESS**"  # Add your GDB path here

walk = arcpy.da.Walk(datatype="FeatureClass")

for dir_path, dir_names, file_names in walk:
    for filename in file_names:
        if filename.endswith('.shp'):
            print(filename)

walk = arcpy.da.Walk(datatype="FeatureClass")
for dir_path, dir_names, file_names in walk:
    for filename in file_names:
        if filename.endswith('.shp'):
            arcpy.env.addOutputsToMap = True                
            arcpy.env.overwriteOutput = True                            
            arcpy.MakeFeatureLayer_management(os.path.join(dir_path, filename),filename)
            # Set up intersect output name
            intersectoutput = os.path.splitext(os.path.basename(filename))[0] + '_inte'  # do not end with .shp since it's being output to the GDB
            # perform intersection. I output the intersection to the geodatabase
            arcpy.Intersect_analysis(filename, os.path.join(gdb, intersectoutput))
            # Import original shapefile into the geodatabase
            arcpy.FeatureClassToGeodatabase_conversion(filename, gdb)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.