问题描述
我正在尝试执行一些地理处理.我的任务是找到一个目录中的所有 shapefile,然后在该目录中找到该 shapefile 的完整路径名.我可以获取 shapefile 的名称,但我不知道如何获取该 shapefile 的完整路径名.
I'm trying to perform some geoprocessing. My task is to locate all shapefiles within a directory, and then find the full path name for that shapefile within the directory. I can get the name of the shapefile, but I don't know how to get the full path name for that shapefile.
shpfiles = []
for path, subdirs, files in os.walk(path):
for x in files:
if x.endswith(".shp") == True:
shpfiles.append[x]
推荐答案
os.walk
为您提供目录的路径作为循环中的第一个值,只需使用 os.path.join()
创建完整的文件名:
os.walk
gives you the path to the directory as the first value in the loop, just use os.path.join()
to create full filename:
shpfiles = []
for dirpath, subdirs, files in os.walk(path):
for x in files:
if x.endswith(".shp"):
shpfiles.append(os.path.join(dirpath, x))
我将循环中的 path
重命名为 dirpath
以免与您已经传递给 os.walk 的
.path
变量冲突()
I renamed path
in the loop to dirpath
to not conflict with the path
variable you already were passing to os.walk()
.
注意不需要测试.endswith() == True
的结果;if
已经为你做了这些,== True
部分是完全多余的.
Note that you do not need to test if the result of .endswith() == True
; if
already does that for you, the == True
part is entirely redundant.
你可以使用 .extend()
和一个生成器表达式来使上面的代码更紧凑:
You can use .extend()
and a generator expression to make the above code a little more compact:
shpfiles = []
for dirpath, subdirs, files in os.walk(path):
shpfiles.extend(os.path.join(dirpath, x) for x in files if x.endswith(".shp"))
甚至作为一种列表理解:
or even as one list comprehension:
shpfiles = [os.path.join(d, x)
for d, dirs, files in os.walk(path)
for x in files if x.endswith(".shp")]
这篇关于需要使用 os.walk() 的特定文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!