Using Glob() function to find files recursivelyglob() or glob. iglob() directly from glob module to retrieve paths recursively from inside the directories/files and subdirectories/subfiles. Note: When recursive is set True “ ** ” followed by path separator ('./**/') will match any files or directories.
Python glob. glob() method returns a list of files or folders that matches the path specified in the pathname argument. This function takes two arguments, namely pathname, and recursive flag. pathname : Absolute (with full path and the file name) or relative (with UNIX shell-style wildcards).
glob (short for global) is used to return all file paths that match a specific pattern. We can use glob to search for a specific file pattern, or perhaps more usefully, search for files where the filename matches a certain pattern by using wildcard characters.
Use os.path.basename(path)
to get the filename.
This might help someone:
names = [os.path.basename(x) for x in glob.glob('/your_path')]
map(os.path.basename, glob.glob("your/path"))
Returns an iterable with all the file names and extensions.
os.path.basename works for me.
Here is Code example:
import sys,glob
import os
expectedDir = sys.argv[1] ## User input for directory where files to search
for fileName_relative in glob.glob(expectedDir+"**/*.txt",recursive=True): ## first get full file name with directores using for loop
print("Full file name with directories: ", fileName_relative)
fileName_absolute = os.path.basename(fileName_relative) ## Now get the file name with os.path.basename
print("Only file name: ", fileName_absolute)
Output :
Full file name with directories: C:\Users\erinksh\PycharmProjects\EMM_Test2\venv\Lib\site-packages\wheel-0.33.6.dist-info\top_level.txt
Only file name: top_level.txt
I keep rewriting the solution for relative globbing (esp. when I need to add items to a zipfile) - this is what it usually ends up looking like.
# Function
def rel_glob(pattern, rel):
"""glob.glob but with relative path
"""
for v in glob.glob(os.path.join(rel, pattern)):
yield v[len(rel):].lstrip("/")
# Use
# For example, when you have files like: 'dir1/dir2/*.py'
for p in rel_glob("dir2/*.py", "dir1"):
# do work
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With