有没有办法在目录上使用glob,获取具有特定扩展名的文件,但只有文件本身,而不是整个路径?
答案 0 :(得分:71)
使用os.path.basename(path)
获取文件名。
答案 1 :(得分:65)
这可能对某人有所帮助:
names = [os.path.basename(x) for x in glob.glob('/your_path')]
答案 2 :(得分:11)
将glob与os.path.basename
结合使用。
答案 3 :(得分:2)
map(os.path.basename, glob.glob("your/path"))
返回带有所有文件名和扩展名的迭代器。
答案 4 :(得分:0)
我一直在重写relative globbing的解决方案(尤其是当我需要向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
答案 5 :(得分:0)
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
答案 6 :(得分: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')]
答案 7 :(得分:0)
for f in glob.glob(gt_path + "/*.png"): # find all png files
exc_name = f.split('/')[-1].split(',')[0]
那么 exc_name
就像 myphoto.png