有没有办法可以在目录上使用glob来获取具有特定扩展名的文件,而只能获取文件名本身,而不是整个路径?
有没有办法可以在目录上使用glob来获取具有特定扩展名的文件,而只能获取文件名本身,而不是整个路径?
Answers:
这可能会帮助某人:
names = [os.path.basename(x) for x in glob.glob('/your_path')]
map(os.path.basename, glob.glob("your/path"))
返回带有所有文件名和扩展名的iterable。
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
我一直在重写解决方案以实现相对相对(尤其是当我需要将项目添加到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