zoukankan      html  css  js  c++  java
  • 获取文件夹下所有文件名

    In [1]:
    import os
    from pathlib import Path
    import glob

    方法1

    In [3]:
    dirpath="D:\test\1"
    #判断是否是目录
    if os.path.isdir(dirpath):
        img_names=[]
        # 获取所有文件名
        dir_names = os.listdir(dirpath)
        for img_name in dir_names:
            # 获取固定后缀文件名
            if os.path.splitext(img_name)[1] == '.jpg':
                img_names.append(img_name)
    else:
        print("路径错误,请输入目录!")
        
    print("dir_names:",dir_names)
    print("img_names:",img_names)
    print("os.path.splitext(img_name):",os.path.splitext(img_names[0]))
    dir_names: ['66734.jpg', '66734.txt', '66991.jpg', '66991.txt', '67046.jpg', '67046.txt', '68248.jpg', '68248.txt', '68351.jpg', '68351.txt', '68550.jpg', '68550.txt']
    img_names: ['66734.jpg', '66991.jpg', '67046.jpg', '68248.jpg', '68351.jpg', '68550.jpg']
    os.path.splitext(img_name): ('66734', '.jpg')

    方法2

    In [4]:
    # 获取所有文件路径
    file_paths=glob.glob(dirpath)
    # 获取固定后缀文件路径
    img_paths=glob.glob(dirpath+"\*.jpg")
    print("file_paths:",file_paths)
    print("img_paths:",img_paths)
    file_paths: ['D:\test\1']
    img_paths: ['D:\test\1\66734.jpg', 'D:\test\1\66991.jpg', 'D:\test\1\67046.jpg', 'D:\test\1\68248.jpg', 'D:\test\1\68351.jpg', 'D:\test\1\68550.jpg']

    方法3

    In [5]:
    # 获取固定后缀文件路径
    image_suffixes = (".jpeg", ".jpg", ".png", ".bmp")
    img_paths=[p for p in Path(dirpath).glob("**/*") if p.suffix.lower() in image_suffixes]
    print("img_paths:",img_paths)
    print("img_paths[0]:",img_paths[0])
    img_paths: [WindowsPath('D:/test/1/66734.jpg'), WindowsPath('D:/test/1/66991.jpg'), WindowsPath('D:/test/1/67046.jpg'), WindowsPath('D:/test/1/68248.jpg'), WindowsPath('D:/test/1/68351.jpg'), WindowsPath('D:/test/1/68550.jpg')]
    img_paths[0]: D:	est166734.jpg
  • 相关阅读:
    ETL Pentaho Data Integration (Kettle) 插入/更新 问题 etl
    Value Investment
    sqlserver 2008r2 表分区拆分问题
    HTTP与HTTPS的区别与联系
    别人分享的面经
    饥人谷开放接口(教程)
    java内存泄漏
    单例模式
    Maven项目上有小红叉咋办
    Socket通信1.0
  • 原文地址:https://www.cnblogs.com/forest128/p/14091619.html
Copyright © 2011-2022 走看看