需要仅返回目录名称的代码
我是一名Python新手,最近得到了一段脚本,这段脚本可以让用户输入一个文件夹的路径,里面存放着一些shapefile文件(比如:c:\programfiles\shapefiles)。然后,它会在每个shapefile里创建一个字段,并把用户输入的文件夹路径和shapefile的名字加进去(比如:c:\programfiles\shapefiles\name.shp)。我想把这个字段填充为仅仅是文件夹的名字(比如:shapefiles)。我知道有一个命令可以分割文件夹的名字,但我该如何把这个名字作为一个函数返回呢?提前谢谢大家。
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)
2 个回答
0
import os
def getparentdirname(path):
if os.path.isfile(path):
dirname = os.path.dirname(path)
return os.path.basename(dirname[0:-1] if dirname.endswith("\\") else dirname)
else:
return os.path.basename(path[0:-1] if dirname.endswith("\\") else path)
这样做应该可以解决问题——不过这需要你电脑上有那个路径(这样os.path.isfile才能检查这个路径是不是一个文件或文件夹)。
1
相关函数: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]