Bootstrap

python 中的os glob等路径解析操作

import os
from glob import glob

def test_os_walk(dir):
    for root, dirs, files in os.walk(dir):
        for file in files:
            file_path = os.path.join(root, file)
            print(file_path)
            if os.path.exists(file_path):
                dirname = os.path.dirname(file_path)
                basename = os.path.basename(file_path)
                print(dirname)
                print(basename)
                
                split_res = os.path.split(file_path)
                print('split_res ', split_res)
                res = os.path.splitext(basename)
                print('splitext ', res)
            
def test_list_dir(directory):
    for file in os.listdir(directory):
        file_path = os.path.join(directory, file)
        if os.path.isdir(file_path):
            test_list_dir(file_path)
        else:
            print(file_path)
            
def test_glob(dir):
    src_paths = glob(os.path.join(dir,"*"))
    print(src_paths)
    
def test_glob2(dir):
    src_paths = glob(os.path.join(dir,"*/*"))
    print(src_paths)
if __name__ == '__main__':
    dir = '/newnfs/dataset/OCR/parking_number_only/big_ocr_zm_format'
    test_os_walk(dir)
    # test_list_dir(dir)
    # test_glob(dir)
    # test_glob2(dir)

运行结果

注意splitext 的文件名后缀带点 .json .bmp, .jpg

;