Select to view content in your preferred language

Utilizing Functions with Arcpy

772
1
11-12-2018 03:28 PM
JackJenkins
Emerging Contributor
I need to re-structure my script so the line & feature class creation happen in functions 
rather than the being spelled out in the main part of my script. I then, need to separate 
the function into a separate file and make the adjustments necessary in the main script to 
allow it to still utilize the functions.
My script;


# Use a .txt file to generate a line shapefile
import arcpy
from collections import defaultdict
import pandas as pd  

outFolder= "C:\\Data"
arcpy.env.workspace = outFolder 

#Read textfile and store in dictionary
df = pd.read_csv(r"C:\\Data\\WalkingPaths.txt", header=None,names=["WalkingPath", "X", "Y"])  
d = defaultdict(list)
for index, row in df.iterrows():    
    d[row["WellPath"]].append(arcpy.Point(row["X"],row["Y"]))

#Create feature class
fc = "WalkingPaths.shp"spatRef = arcpy.SpatialReference(26913)
arcpy.CreateFeatureclass_management(out_path=outFolder, out_name=fc, geometry_type = "POLYLINE", spatial_reference=spatRef)
arcpy.AddField_management (in_table = fc, field_name = "WalkingPath", field_type = "TEXT")

#Insert polylines and attribute
insertCursor = arcpy.da.InsertCursor (fc, ["SHAPE@","WalkingPath"])
for ranch, points in d.iteritems(): #d.items() in python 3    
    insertCursor.insertRow([arcpy.Polyline(arcpy.Array(points)),ranch])

del insertCursor
0 Kudos
1 Reply
MarisaClaggett
Frequent Contributor

Hi Jack,

If you want to call a function created in another script, you can save each file in the same directory and call the module (script with function) in the second script. 

Import Python Script Into Another? - Stack Overflow 

For example:

1st script:

#script name is module1

import arcpy

def test():
    print("This is a test!!")

if __name__ == '__main__':
    test()

2nd script:

#script name is module2

import arcpy
import module1

module1.test()

print("Done!")

Creating functions in python:

https://www.w3schools.com/python/python_functions.asp 

Let me know if this is helpful!

Thanks,

Marisa