不论文件扩展名如何,均使用相同名称获取文件

不论文件扩展名如何,均使用相同名称获取文件,第1张

不论文件扩展名如何,均使用相同名称获取文件

您可以使用该

fnmatch.filter()
函数来识别感兴趣的文件名

import os, fnmatchdef get_all_files(path, pattern):    datafiles = []    for root,dirs,files in os.walk(path):        for file in fnmatch.filter(files, pattern): pathname = os.path.join(root, file) filesize = os.stat(pathname).st_size datafiles.append([file, pathname, filesize])    return datafilesprint get_all_files('.', 'something.*') # all files named 'something'

但是请注意,通过增加几行代码,也可以使某些通用类支持所有

os.walk()
的关键字参数:

import os, fnmatchdef glob_walk(top, pattern, **kwargs):    """ Wrapper for os.walk() that filters the files returned        with a pattern composed of Unix shell-style wildcards        as documented in the fnmatch module.    """    for root, dirs, files in os.walk(top, **kwargs):        yield root, dirs, fnmatch.filter(files, pattern)# sample usagedef get_all_files(path, pattern):    for root, dirs, files in glob_walk(path, pattern):        for file in files: pathname = os.path.join(root, file) filesize = os.stat(pathname).st_size yield file, pathname, filesizeprint list(get_all_files('.', 'something.*')) # all files named 'something'

请注意,此版本中的新

glob_walk()
函数(与wll一样
get_all_files()
)是生成器,就像
os.walk()



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5667545.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存