'Python Glob without the whole path - only the filename

Is there a way I can use glob on a directory, to get files with a specific extension, but only the filename itself, not the whole path?



Solution 1:[1]

Use os.path.basename(path) to get the filename.

Solution 2:[2]

This might help someone:

names = [os.path.basename(x) for x in glob.glob('/your_path')]

Solution 3:[3]

map(os.path.basename, glob.glob("your/path"))

Returns an iterable with all the file names and extensions.

Solution 4:[4]

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

Solution 5:[5]

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

Solution 6:[6]

If you are looking for CSV file:

file = [os.path.basename(x) for x in glob.glob(r'C:\Users\rajat.prakash\Downloads//' + '*.csv')]

If you are looking for EXCEL file:

file = [os.path.basename(x) for x in glob.glob(r'C:\Users\rajat.prakash\Downloads//' + '*.xlsx')]

Solution 7:[7]

for f in glob.glob(gt_path + "/*.png"):  # find all png files
      exc_name = f.split('/')[-1].split(',')[0]

Then the exc_name is like myphoto.png

Solution 8:[8]

None of the existing answers mention using the new pathlib module, which is what I was searching for, so I'll add a new answer here.

Path.glob produces Path objects containing the full path including any directories. If you only need the file names, use the Path.name property.


If you find yourself frequently converting between pathlib and os.path, check out this handy table converting functions between the two libraries.

Solution 9:[9]

Or using pathlib:

from pathlib import Path

dir_URL = Path("your_directory_URL") # e.g. Path("/tmp")
filename_list = [file.name for file in dir_URL.glob("your_pattern")]