Python 需要使用 os.walk() 的特定文件的路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16465399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need the path for particular files using os.walk()
提问by Schack
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.
我正在尝试执行一些地理处理。我的任务是找到一个目录中的所有 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]
采纳答案by Martijn Pieters
os.walkgives you the path to the directory as the first value in the loop, just use os.path.join()to create full filename:
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))
I renamed pathin the loop to dirpathto not conflict with the pathvariable you already were passing to os.walk().
我path在循环中重命名为dirpath与path您已经传递给的变量不冲突os.walk()。
Note that you do not need to test if the result of .endswith() == True; ifalready does that for you, the == Truepart is entirely redundant.
请注意,您不需要测试结果是否为.endswith() == True; if已经为您做到了,这== True部分完全是多余的。
You can use .extend()and a generator expression to make the above code a little more compact:
您可以使用.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"))
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")]
回答by gsmaker
Seems os.path.abspath(finename)will work. Please try.
似乎os.path.abspath(finename)会起作用。请尝试。
shpfiles = []
for path, subdirs, files in os.walk(path):
for x in files:
if x.endswith(".shp") == True:
shpfiles.append(os.path.join(path, x))
回答by kiriloff
Why not import glob?
为什么不import glob呢?
import glob
print(glob.glob('F:\OTHERS\PHOTOS\Panama\mai13*\*.jpg') )
and i get all the jpeg i want, with absolute path
我得到了我想要的所有 jpeg,带有绝对路径
>>>
['F:\OTHERS\PHOTOS\Panama\mai13\03052013271.jpg',
'F:\OTHERS\PHOTOS\Panama\mai13\05052013272.jpg',
'F:\OTHERS\PHOTOS\Panama\mai13\05052013273.jpg']

