Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] 
like image 765
Schack Avatar asked May 09 '13 15:05

Schack


People also ask

How do I find the path of a specific file?

To view the full path of an individual file: Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document.

What does os Walk () do?

OS. walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

How do you set the path of a file?

To use a relative path, type ". \" to specify the first file path in the list, and then type the name of the subfolder. For example, if the first file path in the list is F:\Gainseek\Data\, then the path .

Does os walk Change directory?

walk() never changes the current directory, and assumes that its caller doesn't either.


1 Answers

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")] 
like image 61
Martijn Pieters Avatar answered Oct 28 '22 20:10

Martijn Pieters