Select to view content in your preferred language

Removing characters from a Feature Class file name

4243
12
Jump to solution
02-14-2021 01:25 PM
MichaelTomiak
Occasional Contributor

This should be a simple answer ... I'm trying to just remove the first 25 characters from a list (>90 in number) of Feature classes (raster datasets) within a .gdb.

All the file names are named the same except for the last 9 digits (hence why I am trying to remove the first 25).
I would then like to add some standard text to all the FCs (in the example "Hello")

 

My attempt from other threads comprises the following (but has not worked so far):

-------------------

import arcpy
import os

dir = r'C:\Users\X\Desktop\X\X.gdb'


arcpy.env.workspace = dir

for ras in arcpy.ListRasters ("*"):
print (ras)    #original raster name
basename = ras.split("*")[:25]    #strips the first 25 characters from original raster name
newrastername = "Hello" + basename
print (newrastername)
arcpy.CopyRaster_management(ras, newrastername)   #create a new raster with the new/updated name

----------------------

Error received:

---------------------------------------------------------------------------
SyntaxError                               Traceback (most recent call last)
File C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\ast.py, in parse:
Line 35:    return compile(source, filename, mode, PyCF_ONLY_AST)

SyntaxError: Missing parentheses in call to 'print'. Did you mean print(ras #original raster name)? (<string>, line 😎

 

0 Kudos
12 Replies
DanPatterson
MVP Esteemed Contributor

Code formatting on the esri Community will help

Code formatting ... the Community Version - GeoNet, The Esri Community


... sort of retired...
MichaelTomiak
Occasional Contributor

Cheers Dan. This is really helpful as I am definitely not a coder and learning/applying only the very basics of Python to help me with the GIS aspect of my technical work. 

 

I used Rename tool for this with %Name% in the output name field originally, but that's only helpful for appending information and not (as my original Question suggestions) that helpful for removing, or slicing up filenames.

 

0 Kudos
by Anonymous User
Not applicable

Simple oneliner for fun, IF the 25 characters are all the same.

newrastername = ras.replace('THISIS25CHARACTERSLONGMAN', 'Hello')