Python Glob without the whole path – only the filename

Python Programming

Question or problem about Python programming:

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?

How to solve the problem:

Solution 1:

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

Solution 2:

This might help someone:

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

Solution 3:

Use glob in combination with os.path.basename.

Solution 4:

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

Returns an iterable with all the file names and extensions.

Solution 5:

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 6:

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

Solution 7:

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')]

Hope this helps!