码迷,mamicode.com
首页 > 编程语言 > 详细

Python 之 glob读取路径下所有文件夹或文件方法

时间:2015-08-15 18:22:50      阅读:424      评论:0      收藏:0      [点我收藏+]

标签:glob   unix shell   join   extend   python   

    在python中,glob模块是用来查找匹配的文件的
    在查找的条件中,需要用到Unix shell中的匹配规则:
       *    :   匹配所所有
       ?    :   匹配一个字符
       *.*  :   匹配如:[hello.txt,cat.xls,xxx234s.doc]
       ?.*  :   匹配如:[1.txt,h.py]
       ?.gif:   匹配如:[x.gif,2.gif]

    如果没有匹配的,glob.glob(path)将返回一个空的list:[]

import glob  
def get_all():  
    '''''获取目录[F:\\wfpdm\\My_Proc_Data_ZXTZ]下面所有的文件'''  
    return glob.glob('F:\\wfpdm\\My_Proc_Data_ZXTZ\\*.*')  
def get_my_file():  
    '''''获取目录[F:\\wfpdm\\My_Proc_Data_ZXTZ]下面文件名为4个字符的文件'''  
    return glob.glob('F:\\wfpdm\\My_Proc_Data_ZXTZ\\????.txt')
def get_batch_file():  
    '''''获取目录[F:\\wfpdm\\My_Proc_Data_ZXTZ]下面扩展名为\'.txt\'的文件'''  
    return glob.glob('F:\\wfpdm\\My_Proc_Data_ZXTZ\\*.txt')  
def main():  
    print('获取目录[F:\\wfpdm\\My_Proc_Data_ZXTZ]下面所有的文件:')
    tem_files = get_all()  
    print(tem_files)  
    print('获取目录[F:\\wfpdm\\My_Proc_Data_ZXTZ]下面文件名为4个字符的文件:')  
    tem_files = get_my_file()  
    print(tem_files)  
    print('获取目录[F:\\wfpdm\\My_Proc_Data_ZXTZ]下面扩展名为\'.txt\'的文件:')  
    tem_files = get_batch_file()  
    print(tem_files)  
if __name__ == '__main__':  
    main()  


另,也可采用join方法实现文件的获取。

from os.path import exists, isdir, basename, join, splitext
from glob import glob
EXTENSIONS = ['.zxtz']
def get_categories(datasetpath):
    '''得到所有分类,文件夹名称'''
    cat_paths = [files
                 for files in glob(datasetpath + "/*")
                  if isdir(files)]
    cat_paths.sort()
    cats = [basename(cat_path) for cat_path in cat_paths]
    return cats
def get_files(path, extensions=EXTENSIONS):
    '''返回分类路径path下的所有视频文件名,list'''
    all_files = []
    all_files.extend([join(path, basename(fname))
                    for fname in glob(path + "/*")
                    if splitext(fname)[1] in extensions])
    return all_files



版权声明:本文为博主原创文章,未经博主允许不得转载。

Python 之 glob读取路径下所有文件夹或文件方法

标签:glob   unix shell   join   extend   python   

原文地址:http://blog.csdn.net/u013630349/article/details/47683293

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!