没有完整路径的Python Glob-仅文件名


82

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

python  glob 

Answers:






1

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)

输出:

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

您混淆了变量名:绝对表示完整路径;relative仅表示基本名称。
omatai '20

0

我一直在重写解决方案以实现相对相对(尤其是当我需要将项目添加到zipfile中时)-这通常最终看起来像这样。

# 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

如果您正在寻找CSV文件:

file = [os.path.basename(x) for x in glob.glob(r'C:\Users\rajat.prakash\Downloads//' + '*.csv')]

如果您正在寻找EXCEL文件:

file = [os.path.basename(x) for x in glob.glob(r'C:\Users\rajat.prakash\Downloads//' + '*.xlsx')]
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.