栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您可以使用该

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()



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661429.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号