我能否在目录上使用glob,获取特定扩展名的文件,但只返回文件名本身,不包括整个路径?
old = os.getcwd(); os.chdir(dir); files = glob.glob('**/*.txt'); os.chdir(old)
。 - milahumap(os.path.basename, glob.glob("your/path"))
返回一个包含所有文件名和扩展名的可迭代对象。对我来说,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
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")]
# 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
现有的答案中没有提到使用新的pathlib
模块,这正是我所寻找的,因此我将在此添加一个新答案。
Path.glob
生成包含完整路径(包括任何目录)的Path
对象。如果你只需要文件名,请使用Path.name
属性。
如果你经常在pathlib
和os.path
之间进行转换,请查看这个方便的表格,它可以在两个库之间转换函数。
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')]
import glob
a=glob.glob("*.pkl")
该函数返回以.pkl结尾的每个文件的完整路径列表。
现在你可以使用以下方法删除路径信息并仅提取列表项的文件名:
import os
b=os.path.basename(a[0])
# This is an example to extract filename for only one list item
bb=[os.path.basename(list_item) for list_item in a]
for f in glob.glob(gt_path + "/*.png"): # find all png files
exc_name = f.split('/')[-1].split(',')[0]
然后exc_name
就像myphoto.png
"sql/*.sql"
。os.listdir
函数实际上会列出相对于给定目录的文件路径,但它无法处理模式。编辑:啊,我正在寻找这个答案:https://dev59.com/TlcO5IYBdhLWcg3w-V_0#44994860 技巧是使用os.path.relpath
而不是basename
。 - Leonid