2

I am trying to add xy data into the attribute tables of 2 point layers, then export the tables into 2 separate excel tables using this code:

env.workspace = r"G:\PROJECTS\osfie\gis\lyr"
lyr1 = r"G:\PROJECTS\osfie\gis\lyr\karka.shp"
lyr2 = r"G:\PROJECTS\osfie\gis\lyr\gaskarka.shp"
arcpy.AddXY_management(lyr1)
arcpy.AddXY_management(lyr2)
arcpy.TableToExcel_conversion(lyr1,
                          r"G:\Users\yaron\Downloads\karka.xls")

arcpy.TableToExcel_conversion(lyr2,
                          r"G:\Users\yaron\Downloads\gaskarka.xls")

This works just fine. But when I try to build a function in order to avoid this clumsy code, and get faster code- I get stuck:

def xy(lyr1,env):
    env.workspace = r"G:\PROJECTS\osfie\gis\lyr"
    lyr1 = r"G:\PROJECTS\osfie\gis\lyr\karka.shp"
    arcpy.AddXY_management(lyr1)
    arcpy.TableToExcel_conversion(lyr1,
                          r"G:\Users\yaron\Downloads\karka.xls")
print xy(lyr1,env)
  • 1
    Do you want to call the function with path of lyr and env, for example xy(r'C:\folder\shape.shp', r'C:\folder')? Then dont assign them values inside the function. – BERA Mar 13 '18 at 10:40
  • yes BERA, but i want to do it at the same time for 2 layers – newGIS Mar 13 '18 at 10:45
  • The purpose of the function is to be re-used. If you just want to apply the same action to iterable objects, a loop is sufficient. – GISGe Mar 13 '18 at 11:19
3

There shouldn't be any dynamic variable inside the function. First create the function with generic variables, and replace those variables with values when you call the function. And the env variable is not necessary here:

import arcpy, os

def xy(lyr):
    shp_name = os.path.split(lyr)[-1]
    xls_name = os.path.join(r"G:\Users\yaron\Downloads", shp_name.replace(".shp", ".xls"))
    arcpy.AddXY_management(lyr)
    arcpy.TableToExcel_conversion(lyr, xls_name)


xy(r"G:\PROJECTS\osfie\gis\lyr\karka.shp")
xy(r"G:\PROJECTS\osfie\gis\lyr\gaskarka.shp")
1

If you want to call the function with path to shape and excelfile dont assign them values inside the function:

def xy(featureclasses, outfolder):
    import arcpy, os
    for fc in featureclasses:
        arcpy.AddXY_management(fc)
        arcpy.TableToExcel_conversion(fc,os.path.join(outfolder,os.path.basename(fc).split('.')[0])+'.xls')

xy([r'C:\Default.gdb\Features_10000',r'C:\Folder\Features_20000.shp'], r'C:\Test')

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.