Issue
basically, as the title says, I want to be able to use a python script where I give a path/directory, and a file name, and it will search all the way through the path/directory just to find the file name.
I have tried using glob.glob()
however it will only search within the directory and not within subfolders and such from what I have found.
Solution
From the glob.glob()
docs (emphasis mine), starting at Python 3.5:
If
recursive
is true, the pattern"**"
will match any files and zero or more directories, subdirectories and symbolic links to directories.
So you just put **
into your pattern where you want it to expand to any subdirectories and files therein and add recursive=True
as a keyword argument.
For example, given a directory structure like
a
+-b
| +-d
| +-f
+-c
+-e
with your current working directory being a
, you can do:
>>> from glob import glob
>>> glob("**", recursive=True)
['c', 'c/e', 'b', 'b/d', 'b/d/f']
For your specific use case of searching for a filename in all subdirectories, you'd do:
>>> glob("**/f", recursive=True)
['b/d/f']
Note that **
patterns also work in pathlib.Path.glob()
and pathlib
paths are often more comfortable to use than the more low-level os.path
and glob
modules.
Answered By - smheidrich
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.