需要代码才能返回目录名称

时间:2010-09-20 18:42:56

标签: python file split

我是一个python新手,并获得了一个允许用户输入目录的脚本 shapefile所在的位置(例如,c:\ programfiles \ shapefiles)。然后,它在每个shapefile中创建一个字段,并添加输入的目录路径和shapefile名称(例如,c:\ programfiles \ shapefiles \ name.shp)。我想用刚刚填充这个领域 目录名称(例如,shapefile)。我知道有一个命令会拆分目录名,但是如何将basename作为函数返回?提前致谢。

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 :(得分:1)

相关功能:http://docs.python.org/library/os.path.html

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

os.path.dirname(your_full_filename)

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

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

仅限于dirname:

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

答案 1 :(得分: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可以检查路径是文件还是目录)