Python Glob without the whole path - only the filename

前端 未结 7 1874
死守一世寂寞
死守一世寂寞 2020-12-23 10:47

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?

相关标签:
7条回答
  • 2020-12-23 11:24
    map(os.path.basename, glob.glob("your/path"))
    

    Returns an iterable with all the file names and extensions.

    0 讨论(0)
  • 2020-12-23 11:28

    Use glob in combination with os.path.basename.

    0 讨论(0)
  • 2020-12-23 11:35

    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
    
    0 讨论(0)
  • 2020-12-23 11:38

    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
    
    0 讨论(0)
  • 2020-12-23 11:43

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

    0 讨论(0)
  • 2020-12-23 11:45

    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')]
    
    0 讨论(0)
提交回复
热议问题