Select to view content in your preferred language

probles w

435
1
Wednesday
Laura_m_Conner
Regular Contributor

I am creating a python code to iterate through a folder of shapefiles of contour s data  load it and then publish it. as part if the script i am trying to get all the files to have the same line color so when it is published it looks consistent.  my code loads the data but it not applying the same color to all the layers. How would i accomplish this ?

my code is:

import arcpy
import os

# Define the folder containing the files
q=1
folder_path = r"E:\Macon_Bibb_County_Contour2024\Contour 5 ft"
output = f"E:\Macon_Bibb_County_Contour2024\outputs\ 5ft package{q}"
tag ="contour, contour 5 ft, elevation, mwa"
summ = "5 ft vector tile package from macon bidd lidar data flown 2024"
lower=380000
upper=410000

# Define the map and project
project = arcpy.mp.ArcGISProject("CURRENT")  # Use "CURRENT" for the active ArcGIS Pro project
map = project.listMaps()[0]  # Get the first map in the project (adjust if needed)


for dirpath, dirnames, filenames in os.walk(folder_path):
    try:
        for f in filenames:
            i = f[:-4]
            if i.isdigit()  and lower <= int(i) < upper:
                if f.endswith(".shp"):
                    full_path =(str(dirpath) +"\\"+f)
                    #print(full_path)
                    l = map.addDataFromPath(full_path)
                    l.symbology.renderer.symbol.Color = "#824924" #set line color
                    #l.append(full_path)
    except arcpy.ExecuteError:
        # Handle geoprocessing errors
        msgs = arcpy.GetMessages(2)
        arcpy.AddError(msgs)  # Return error messages for script tools
        print(msgs)  # Print error messages
        continue

 

Arc Pro: 3.5.2

 

0 Kudos
1 Reply
HaydenWelch
MVP Regular Contributor

I usually like using Path.rglob for recusrive walking. You also have several errors in your code.

  1. output is an fstring with escaped characters (needs to be fr not just f)
  2. You're accessing a Color attribute of symbol that doesnt exist. It's lowercase color
  3. That color attribute requires a dictionary in the format {'COLORSPACE', [v1,v2,v3,...]}
  4. You're using ExecuteError which I'm not sure you can access after arcpy is initialized?

Here's a version that tries to address those issues:

import arcpy
from pathlib import Path

from typing import TYPE_CHECKING
from collections.abc import Iterator
from arcpy.mp import Map, Layer
if TYPE_CHECKING:
    from arcpy._symbology import Symbology, Symbol
    from arcpy._renderer import SimpleRenderer
from arcpy import ExecuteError #type:ignore

def shapefiles_in(path: Path) -> Iterator[Path]:
    """Walk an rglob of shapefiles"""
    yield from (fl for fl in path.rglob('*.shp') if fl.is_file())
  
def file_range(files: Iterator[Path], lower: int, upper: int) -> Iterator[Path]:
    """Filter shapefiles to filename range  """
    yield from ( fl for fl in files if fl.stem.isdigit() and ( lower <= int(fl.stem) < upper ) )

def add_data(map: Map, shapefile: Path) -> None:
    """Add the shapefile to the map"""
    # This is an unwrapped version of the symbol edit that exposes the base
    # types for each level. It should help you find the issue 
    # (Color is lowercase and needs a dictionary)
    lay: Layer = map.addDataFromPath(str(shapefile.resolve())) #type:ignore
    sym: Symbology = lay.symbology
    rend: SimpleRenderer = sym.renderer #type:ignore
    symbol: Symbol = rend.symbol #type:ignore
    symbol.color = {'RGB': [130, 73, 36]} #"#824924"
  
def main() -> None:
    # Define the folder containing the files
    q=1
    folder_path = Path(r"E:\Macon_Bibb_County_Contour2024\Contour 5 ft")
    output = Path(fr"E:\Macon_Bibb_County_Contour2024\outputs\ 5ft package{q}")
    tag ="contour, contour 5 ft, elevation, mwa"
    summ = "5 ft vector tile package from macon bidd lidar data flown 2024"
    lower=380000
    upper=410000
    
    # Define the map and project
    project = arcpy.mp.ArcGISProject("CURRENT")  # Use "CURRENT" for the active ArcGIS Pro project
    map = project.listMaps()[0]  # Get the first map in the project (adjust if needed)
    
    shps = shapefiles_in(folder_path)
    for fl in file_range(shps, lower, upper):
        try:
            add_data(map, fl)
        except Exception as e:
            # Handle geoprocessing errors
            msgs = arcpy.GetMessages(2)
            arcpy.AddError(msgs)  # Return error messages for script tools
            print(msgs, '\n', e)  # Print error messages
    
if __name__ == '__main__':
    main()
0 Kudos