I am working on a script to recursively go through subfolders in a mainfolder and build a list off a certain file type. I am having an issue with the script. Its currently set as follows
for root, subFolder, files in os.walk(PATH):
for item in files:
if item.endswith(".txt") :
fileNamePath = str(os.path.join(root,subFolder,item))
the problem is that the subFolder variable is pulling in a list of subfolders rather than the folder that the ITEM file is located. I was thinking of running a for loop for the subfolder before and join the first part of the path but I figured Id double check to see if anyone has any suggestions before that. Thanks for your help!
I will translate John La Rooy's list comprehension to nested for's, just in case anyone else has trouble understanding it.
Should be equivalent to:
Here's the documentation for list comprehension and the functions os.walk and glob.glob.
glob.glob()
got a new recursive parameter.If you want to get every
.txt
file undermy_path
(recursively including subdirs):If you need an iterator you can use iglob as an alternative:
You should be using the
dirpath
which you callroot
. Thedirnames
are supplied so you can prune it if there are folders that you don't wishos.walk
to recurse into.Edit:
After the latest downvote, it occurred to me that
glob
is a better tool for selecting by extension.Also a generator version
Edit2 for Python 3.4+
The new
pathlib
library simplifies this to one line:You can also use the generator version:
This returns
Path
objects, which you can use for pretty much anything, or get the file name as a string byfile.name
.Its not the most pythonic answer, but I'll put it here for fun because it's a neat lesson in recursion
On my machine I have two folders,
root
androot2
Lets say I want to find all
.txt
and all.mid
files in either of these directories, then I can just do