如何删除文件基名称的一部分并将其附加到文件名的末尾?

2024-07-05 14:44:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个文件中有多个要素类,需要根据指定的文件重新投影它们。我正在编写一个Arcpy脚本(将用于在Arcmap中创建一个工具)来实现这一点

如何删除文件名的开头并将其添加到结尾?您可以看到,为了运行arcpy.Project_management工具,我必须指定output\u feature\u类前面有一个文本字符串,以便正确使用该工具。例如,我不需要说“projected\u shapeFile.shp”,而是需要说shapeFile\u projected.shp

我为此编写了一个“for”循环,所以我想对所有被重投影的要素类都这样做

#Import modules
import arcpy, os

#Set workspace directory
from arcpy import env

#Define workspace
inWorkspace = arcpy.GetParameterAsText(0)
env.workspace = inWorkspace
env.overwriteOutput = True

#Define local feature class to reproject to
targetFeature = arcpy.GetParameterAsText(1)

#Describe the input feature class 
inFc = arcpy.Describe(targetFeature)
sRef = inFc.spatialReference

#Describe input feature class
fcList = arcpy.ListFeatureClasses()

#Loop to re-define the feature classes
for fc in fcList:
    desc = arcpy.Describe(fc)
    if desc.spatialReference.name != sRef.name:
        print "Projection of " + str(fc) + " is " + desc.spatialReference.name + ", so re-defining projection now:\n"
        newFc = arcpy.Project_management(fc, "projected_" + fc, sRef)
        arcpy.AddMessage(arcpy.GetMessages())
        newFc = arcpy.Describe(newFc)
        count = arcpy.GetMessageCount()
        print "The reprojection of " + str(newFc.baseName) + " " + arcpy.GetMessage(count-1) + "\n"

我还想在打印邮件时从名称中删除“.shp”,可以吗


Tags: 工具toenvdescworkspacefeatureclassfc
1条回答
网友
1楼 · 发布于 2024-07-05 14:44:35

我不知道哪个语句给出了文件名。 用给出输出的语句替换输入

name = "projected_shapeFile.shp" #here add the statement that outputs the filename 
name = name[:name.find('.')] #skip this if you want to keep ".shp" extension
name = name.split('_')
name = name[1] +'_' +name[0]
name
'shapeFile_projected'

循环内部:

#Loop to re-define the feature classes
for fc in fcList:
    desc = arcpy.Describe(fc)
    if desc.spatialReference.name != sRef.name:
        print "Projection of " + str(fc) + " is " + desc.spatialReference.name + ", so re-defining projection now:\n"
        newFc = arcpy.Project_management(fc, "projected_" + fc, sRef)
        newFc = newFc[:name.find('.')] #skip this if you want to keep ".shp" extension
        newFc = name.split('_')
        newFc = newFc[1] +'_' +newFc[0]
        arcpy.AddMessage(arcpy.GetMessages())
        newFc = arcpy.Describe(newFc)
        count = arcpy.GetMessageCount()
        print "The reprojection of " + str(newFc.baseName) + " " + arcpy.GetMessage(count-1) + "\n"

相关问题 更多 >