Python Glob without the whole path - only the filename

This might help someone:

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


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


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

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

Returns an iterable with all the file names and extensions.

Tags:

Python

Glob