gpt4 book ai didi

python - 需要代码仅返回目录名称

转载 作者:太空宇宙 更新时间:2023-11-03 19:35:32 24 4
gpt4 key购买 nike

我是一个Python新手,并且已经获得了一个让用户输入目录的脚本shapefile 所在的位置(例如 c:\programfiles\shapefiles)。然后,它在每个 shapefile 中创建一个字段,并添加输入的目录路径和 shapefile 名称(例如,c:\programfiles\shapefiles\name.shp)。我想用以下内容填充该字段目录名称(例如 shapefile)。我知道有一个命令可以分割目录名称,但是如何将基本名称作为函数返回?提前致谢。

import sys, string, os, arcgisscripting
gp = arcgisscripting.create()

# this is the directory user must specify
gp.workspace = sys.argv[1]
# declare the given workspace so we can use it in the update field process
direct = gp.workspace
try:
fcs = gp.ListFeatureClasses("*", "all")
fcs.reset()
fc = fcs.Next()


while fc:
fields = gp.ListFields(fc, "Airport")
field_found = fields.Next()
# check if the field allready exist.
if field_found:
gp.AddMessage("Field %s found in %s and i am going to delete it" % ("Airport", fc))
# delete the "SHP_DIR" field
gp.DeleteField_management(fc, "Airport")
gp.AddMessage("Field %s deleted from %s" % ("Airport", fc))
# add it back
gp.AddField_management (fc, "Airport", "text", "", "", "50")
gp.AddMessage("Field %s added to %s" % ("Airport", fc))
# calculate the field passing the directory and the filename
gp.CalculateField_management (fc, "Airport", '"' + direct + '\\' + fc + '"')
fc = fcs.Next()


else:
gp.addMessage(" layer %s has been found and there is no Airport" % (fc))
# Create the new field
gp.AddField_management (fc, "Airport", "text", "", "", "50")
gp.AddMessage("Field %s added to %s" % ("Airport", fc))

# Apply the directory and filename to all entries
gp.CalculateField_management (fc, "Airport", '"' + direct + '\\' + fc + '"')
fc = fcs.Next()
gp.AddMessage("field has been added successfully")
# Remove directory

except:
mes = gp.GetMessages ()
gp.AddMessage(mes)

最佳答案

相关函数:http://docs.python.org/library/os.path.html

对于包含父路径(如果可用)的目录名:

os.path.dirname(your_full_filename)

对于包含绝对父路径的目录名:

os.path.dirname(os.path.abspath(your_full_filename))

仅用于目录名:

os.path.split(os.path.dirname(your_full_filename))[-1]

关于python - 需要代码仅返回目录名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3754439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com