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

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 … Read more

Non-recursive os.walk()

Add a break after the filenames for loop: for root, dirs, filenames in os.walk(workdir): for fileName in filenames: print (fileName) break #prevent descending into subfolders This works because (by default) os.walk first lists the files in the requested folder and then goes into subfolders.

Filtering os.walk() dirs and files

This solution uses fnmatch.translate to convert glob patterns to regular expressions (it assumes the includes only is used for files): import fnmatch import os import os.path import re includes = [‘*.doc’, ‘*.odt’] # for files only excludes = [‘/home/paulo-freitas/Documents’] # for dirs and files # transform glob patterns to regular expressions includes = r’|’.join([fnmatch.translate(x) for … Read more

How to do a recursive sub-folder search and return files in a list?

You should be using the dirpath which you call root. The dirnames are supplied so you can prune it if there are folders that you don’t wish os.walk to recurse into. import os result = [os.path.join(dp, f) for dp, dn, filenames in os.walk(PATH) for f in filenames if os.path.splitext(f)[1] == ‘.txt’] Edit: After the latest … Read more

tech