Python Glob without the whole path - only the filename

PythonGlob

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

This might help someone:

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

Solution 3 - Python

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

Returns an iterable with all the file names and extensions.

Solution 4 - Python

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 - Python

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 - Python

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 - Python

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 - Python

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 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser825286View Question on Stackoverflow
Solution 1 - PythonTom ZychView Answer on Stackoverflow
Solution 2 - PythonAnastasios AndronidisView Answer on Stackoverflow
Solution 3 - PythonVíctor NavarroView Answer on Stackoverflow
Solution 4 - Pythonrinkush shardaView Answer on Stackoverflow
Solution 5 - PythonturtlemonvhView Answer on Stackoverflow
Solution 6 - Pythonrajat prakashView Answer on Stackoverflow
Solution 7 - PythonNiceView Answer on Stackoverflow
Solution 8 - PythonLeland HepworthView Answer on Stackoverflow
Solution 9 - PythonStefan G.View Answer on Stackoverflow