Reputation: 157
I'm using os.walk(directory) to show recursively all the files from that directory. The thing is that i need to show only the files that contain an asked String in its name, and it has to manage metachars too.
What i have now is:
for root, subdirs, files in os.walk(dir1):
for filename in files:
if substring in filename:
name_path = os.path.join(root,filename)
list.insert(END, name_path)
This works nicely, but if substring = *
, as i dont have files containing an ' * ', my list is empty.
So, how do I get this to work if substring
contains a METACHAR?
Upvotes: 13
Views: 137480
Reputation: 616
You can use glob. It's very handy and similar to find command in Linux.
import glob
glob.glob("/home/user/*.txt")
Search in multiple subdirectories
glob.glob("/home/user/*/*.txt")
or
glob.glob("/home/user/logs?.txt")
Upvotes: 4
Reputation: 2242
I think you are looking for fnmatch:
https://docs.python.org/3/library/fnmatch.html#module-fnmatch
Upvotes: 18