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

前端 未结 3 1923
独厮守ぢ
独厮守ぢ 2020-12-25 12:27

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.

相关标签:
3条回答
  • 2020-12-25 12:43

    Why not import glob ?

    import glob 
    
    print(glob.glob('F:\OTHERS\PHOTOS\Panama\\mai13*\\*.jpg') )
    

    and i get all the jpeg i want, with absolute path

    >>> 
    ['F:\\OTHERS\\PHOTOS\\Panama\\mai13\\03052013271.jpg', 
    'F:\\OTHERS\\PHOTOS\\Panama\\mai13\\05052013272.jpg', 
    'F:\\OTHERS\\PHOTOS\\Panama\\mai13\\05052013273.jpg']
    
    0 讨论(0)
  • 2020-12-25 12:48

    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")]
    
    0 讨论(0)
  • 2020-12-25 13:06

    Seems os.path.abspath(finename) will work. Please try.

    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))
    
    0 讨论(0)
提交回复
热议问题