Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

python - Need the path for particular files using os.walk()

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

I renamed path in the loop to dirpath to not conflict with the path variable you already were passing to os.walk().

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.

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")]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...