i working on script recursively go through subfolders in mainfolder , build list off file type. having issue script. set follows
for root, subfolder, files in os.walk(path): item in files: if item.endswith(".txt") : filenamepath = str(os.path.join(root,subfolder,item))
the problem subfolder variable pulling in list of subfolders rather folder item file located. thinking of running loop subfolder before , join first part of path figured id double check see if has suggestions before that. help!
you should using dirpath
call root
. dirnames
supplied can prune if there folders don't wish os.walk
recurse into.
import os result = [os.path.join(dp, f) dp, dn, filenames in os.walk(path) f in filenames if os.path.splitext(f)[1] == '.txt']
edit:
after latest downvote, occurred me glob
better tool selecting extension.
import os glob import glob result = [y x in os.walk(path) y in glob(os.path.join(x[0], '*.txt'))]
also generator version
from itertools import chain result = (chain.from_iterable(glob(os.path.join(x[0], '*.txt')) x in os.walk('.')))