1. 程式人生 > >Python 之 glob讀取路徑下所有資料夾或檔案方法

Python 之 glob讀取路徑下所有資料夾或檔案方法

    在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