使用os.walk()需要特定文件的路径

Sch*_*ack 23 python os.walk shapefile

我正在尝试执行一些地理处理.我的任务是在目录中找到所有shapefile,然后在目录中找到该shapefile的完整路径名.我可以获取shapefile的名称,但我不知道如何获取该shapefile的完整路径名.

shpfiles = []
for path, subdirs, files in os.walk(path):
    for x in files:
        if x.endswith(".shp") == True:
            shpfiles.append[x]
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 62

os.walk为您提供目录的路径作为循环中的第一个值,只是用于os.path.join()创建完整的文件名:

shpfiles = []
for dirpath, subdirs, files in os.walk(path):
    for x in files:
        if x.endswith(".shp"):
            shpfiles.append(os.path.join(dirpath, x))
Run Code Online (Sandbox Code Playgroud)

path在循环中重命名dirpath为不与path您传递给的变量冲突os.walk().

请注意,您不需要测试结果是否.endswith() == True; if已经为你做了这件事,这== True部分完全是多余的.

您可以使用.extend()和生成器表达式使上面的代码更紧凑:

shpfiles = []
for dirpath, subdirs, files in os.walk(path):
    shpfiles.extend(os.path.join(dirpath, x) for x in files if x.endswith(".shp"))
Run Code Online (Sandbox Code Playgroud)

甚至作为一个列表理解:

shpfiles = [os.path.join(d, x)
            for d, dirs, files in os.walk(path)
            for x in files if x.endswith(".shp")]
Run Code Online (Sandbox Code Playgroud)