Python Glob without the whole path – only the filename

Question:

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?

Asked By: user825286

||

Answers:

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

Answered By: Tom Zych

This might help someone:

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

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
Answered By: turtlemonvh

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:UserserinkshPycharmProjectsEMM_Test2venvLibsite-packageswheel-0.33.6.dist-infotop_level.txt
Only file name:  top_level.txt
Answered By: rinkush sharda
map(os.path.basename, glob.glob("your/path"))

Returns an iterable with all the file names and extensions.

Answered By: Víctor Navarro

If you are looking for CSV file:

file = [os.path.basename(x) for x in glob.glob(r'C:Usersrajat.prakashDownloads//' + '*.csv')]

If you are looking for EXCEL file:

file = [os.path.basename(x) for x in glob.glob(r'C:Usersrajat.prakashDownloads//' + '*.xlsx')]
Answered By: rajat prakash
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

Answered By: Nice

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.

Answered By: Leland Hepworth

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")]
Answered By: burn4science

Use glob.glob("*.filetype") to get a list of all files with complete path and use os.path.basename(list_item) to remove the extra path and retain only the filename.

Here is an example:

import glob
a=glob.glob("*.pkl")

It returns a list with the complete path of each file ending with .pkl

Now you can remove the path information and extract only the filename for an list item using:

import os
b=os.path.basename(a[0]) 
# This is an example to extract filename for only one list item

If you need to create an entire list with only the filename:

bb=[os.path.basename(list_item) for list_item in a]
Answered By: Binod
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.