New to Python

1784
13
Jump to solution
03-14-2023 12:46 PM
ChrisGlenn
Emerging Contributor

I am having trouble with a file path or the format of the destination I believe. I am very new to Python and have pieced this together with a lot of questions without a strong understanding of ArcGIS yet.

# Imports
import arcpy

# Workspace
trail_data = r"C:\PythonPro\Final\Trail"
county_data = r"C:\PythonPro\Final\Counties\Oregon_Counties.shp"

# Get a list of unique county names
counties = []
with arcpy.da.SearchCursor(county_data, "County_Name") as cursor:
    for row in cursor:
        if row[0] not in counties:
            counties.append(row[0])

# Print the list of counties and ask the user to choose one
print("Choose a county: ")
for i, county in enumerate(counties):
    print(f"{i+1}. {county}")
selection = int(input("> ")) - 1
selected_county = counties[selection]
print("Measuring...")

# Use the selected county to clip the trail data
clip_output = "C:/data/clipped_trails.shp"
where_clause = f"County_Name = '{selected_county}'"
arcpy.Clip_analysis(trail_data, county_data, clip_output, where_clause)

# Calculate the total distance of bike trails in the clipped data
total_distance = 0
with arcpy.da.SearchCursor(clip_output, "SHAPE@LENGTH") as cursor:
    for row in cursor:
        total_distance += row[0]

# Display the total distance to the user
print(f"The total distance of bike trails in {selected_county} is {total_distance:.2f} meters.")

 

 

The error code I am getting is: RuntimeError: Cannot find field 'County_Name'

 

I have tried to change the source and the configuration of the files on my PC. I suspect that the problem is something simple that I am missing, but I am banging my head against a wall and can't see it clearly. Any help is appreciated. Thanks.

 

Chris

Tags (2)
0 Kudos
2 Solutions

Accepted Solutions
Mahdi_Ch
Regular Contributor

I think since it is not obvious that what type of file you are reading (shape file, geodatabase, etc) it is not easy to go further in troubleshooting as that might be the initial issue. 

Then the second issue might be the field (column header) name that you are passing does not exist.  You can check for that like this: 

 

fields = arcpy.ListFields(country_data)  # list of objects
field_names = [i.name for i in fields]  # list of field names
#check if 'Country_Name' is in the list of names
# instead of one field name you can also pass a list of them.
if 'County_Name' in field_names:
    counties = []
    with arcpy.da.SearchCursor(county_data, "County_Name") as cursor:
        for row in cursor:
            if row[0] not in counties:
                counties.append(row[0])
else:
     print('County_Name not in the fields')

 

 

View solution in original post

DavidPike
MVP Frequent Contributor

Line 17 doesn't make much sense.  the error is probably coming from your search cursor.  Are you sure county_name exists in the data rather than being some result of a join on layer object?  Are you also sure county_name is the field name rather than an alias?

View solution in original post

0 Kudos
13 Replies
DavidPike
MVP Frequent Contributor

Please format your code for readability, it's also lost its indentation.  https://community.esri.com/t5/python-blog/code-formatting-the-community-version/ba-p/1007633

Do you know what line it's erroring on? that would save a lot of debugging time.  Perhaps comment out each section and run it sequentially uncommenting lines to see where the error is.

##what is trail data? Looks like a workspace/folder but you're using it as a clip input?
trail_data = r"C:\PythonPro\Trail"

arcpy.Clip_analysis(trail_data, county_data, clip_output, where_clause)

 

0 Kudos
ChrisGlenn
Emerging Contributor
# Imports
import arcpy

# Workspace
trail_data = r"C:\PythonPro\Final\Trail"
county_data = r"C:\PythonPro\Final\Counties\Oregon_Counties.shp"

# Get a list of unique county names
counties = []
with arcpy.da.SearchCursor(county_data, "County_Name") as cursor:
    for row in cursor:
        if row[0] not in counties:
            counties.append(row[0])

# Print the list of counties and ask the user to choose one
print("Choose a county: ")
for i, county in enumerate(counties):
    print(f"{i+1}. {county}")
selection = int(input("> ")) - 1
selected_county = counties[selection]
print("Measuring...")

# Use the selected county to clip the trail data
clip_output = "C:/data/clipped_trails.shp"
where_clause = f"County_Name = '{selected_county}'"
arcpy.Clip_analysis(trail_data, county_data, clip_output, where_clause)

# Calculate the total distance of bike trails in the clipped data
total_distance = 0
with arcpy.da.SearchCursor(clip_output, "SHAPE@LENGTH") as cursor:
    for row in cursor:
        total_distance += row[0]

# Display the total distance to the user
print(f"The total distance of bike trails in {selected_county} is {total_distance:.2f} meters.")
0 Kudos
ChrisGlenn
Emerging Contributor

Apologies for the incorrect format. Here is what I have. I've tried to download the layer I am using as a .shp and .gdb and have had similar issues.

 

Line 17 is where the error code comes from.

 

0 Kudos
DavidPike
MVP Frequent Contributor

Line 17 doesn't make much sense.  the error is probably coming from your search cursor.  Are you sure county_name exists in the data rather than being some result of a join on layer object?  Are you also sure county_name is the field name rather than an alias?

0 Kudos
DanPatterson
MVP Esteemed Contributor

Code formatting ... the Community Version - Esri Community

"county_data"  is a folder, so if it is a geodatabase, then you need to provide the gdb name and the featureclassname.  If it is a shapefile you need the *.shp

eg  county_data = r"C:\PythonPro\Counties.gdb\MyFeatureclass"


... sort of retired...
Mahdi_Ch
Regular Contributor

I think since it is not obvious that what type of file you are reading (shape file, geodatabase, etc) it is not easy to go further in troubleshooting as that might be the initial issue. 

Then the second issue might be the field (column header) name that you are passing does not exist.  You can check for that like this: 

 

fields = arcpy.ListFields(country_data)  # list of objects
field_names = [i.name for i in fields]  # list of field names
#check if 'Country_Name' is in the list of names
# instead of one field name you can also pass a list of them.
if 'County_Name' in field_names:
    counties = []
    with arcpy.da.SearchCursor(county_data, "County_Name") as cursor:
        for row in cursor:
            if row[0] not in counties:
                counties.append(row[0])
else:
     print('County_Name not in the fields')

 

 

Mahdi_Ch
Regular Contributor

By the way , assuming the 'County_Name' exists, if you are looping to get the unique values of that field, there is a faster (at least faster to write) cleaner Pythonic way, by using set.

A set is an unordered collection with no duplicate elements. So basically,  instead of going line by line and assigning the values after checking if they already exist, you can use a "set comprehension" to add all the values to the set function. And then Python set() do the work behind the scene and returns only the unique values for you. 

 

 

 

with arcpy.da.SearchCursor(county_data, "County_Name") as cursor:
    # extracting unique values in the field using Python set function and set comprehension 
    counties= sorted({row[0] for row in cursor}) 

 

 

Then the sorted function -obviously- sorts the values and returns them in a list.

Please follow what @DavidPike  sent you to make your code readable. 

DavidPike
MVP Frequent Contributor

@Mahdi_Ch  I think it would be useful if you explained in the code comments the logic of writing to a set,  would be a good thing to understand for beginners.

Mahdi_Ch
Regular Contributor

David, you are totally right. I edited my post and included the comments.  Thank you for mentioning that.