Python Glob,不包含整个路径-仅包含文件名
有没有一种方法可以在目录上使用glob来获取具有特定扩展名的文件,但只能获取文件名本身,而不是整个路径?使用Python Glob,不包含整个路径-仅包含文件名,python,glob,Python,Glob,有没有一种方法可以在目录上使用glob来获取具有特定扩展名的文件,但只能获取文件名本身,而不是整个路径?使用os.path.basename(path)来获取文件名。将glob与os.path.basename结合使用可能会对某些人有所帮助: names=[glob.glob('/your_path')中x的os.path.basename(x)]我一直在重写解决方案(特别是当我需要向zipfile添加项目时)-这通常是它的最终外观 #函数 def rel_glob(模式,rel): “”“gl
os.path.basename(path)
来获取文件名。将glob与os.path.basename
结合使用可能会对某些人有所帮助:
names=[glob.glob('/your_path')中x的os.path.basename(x)]
我一直在重写解决方案(特别是当我需要向zipfile添加项目时)-这通常是它的最终外观
#函数
def rel_glob(模式,rel):
“”“glob.glob,但具有相对路径
"""
对于glob.glob(os.path.join(rel,pattern))中的v:
收益率v[len(rel):].lstrip(“/”)
#使用
#例如,当您有如下文件时:“dir1/dir2/*.py”
对于rel_glob中的p(“dir2/*.py”,“dir1”):
#工作
通过
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
输出:
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
map(os.path.basename,glob.glob(“您的/path”))
返回包含所有文件名和扩展名的iterable。如果要查找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')]
您混淆了变量名称:绝对表示完整路径;相对仅表示基名称。