没有整个路径的Python Glob - 只有文件名

55 python glob

有没有办法在目录上使用glob,获取具有特定扩展名的文件,但只有文件名本身,而不是整个路径?

Tom*_*ych 85

使用os.path.basename(path)来获取文件名.


Ana*_*dis 80

这可能会帮助某人:

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


orl*_*rlp 12

结合使用glob os.path.basename.


Víc*_*rro 10

map(os.path.basename, glob.glob("your/path"))
Run Code Online (Sandbox Code Playgroud)

返回一个包含所有文件名和扩展名的可迭代对象。


小智 5

os.path.basename 对我有用。

这是代码示例:

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)
Run Code Online (Sandbox Code Playgroud)

输出 :

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
Run Code Online (Sandbox Code Playgroud)


bur*_*nce 5

或者使用路径库:

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")]
Run Code Online (Sandbox Code Playgroud)