随笔 - 836  文章 - 1 评论 - 40 阅读 - 102万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

python  读取文件夹以及文件夹下所有的文件名

复制代码
import os

LISTENER_DIR = os.getenv("LISTENER_DIR", "C:/Users/Sea/Desktop/Sea_Test/")


def get_all_files(dir_path, fileList: list = []):
    listdir = os.listdir(dir_path)
    for file in listdir:
        if os.path.isdir(dir_path + file):
            get_all_files(dir_path + file + "/", fileList)
        else:
            fileList.append(dir_path + file)


if __name__ == '__main__':
    files = []
    get_all_files(LISTENER_DIR, files)
    print(files)
复制代码

 

test:

['C:/Users/Sea/Desktop/Sea_Test/dsadsa/das.tmp', 'C:/Users/Sea/Desktop/Sea_Test/dsadsa/新建文件夹/新建 PPT 演示文稿.ppt', 'C:/Users/Sea/Desktop/Sea_Test/新建 PPT 演示文稿.ppt']

 

 

获取路径中的文件dir  和 文件名

方法一:split

s=r"C:\Users\Desktop\lesson\python\calss1.py"

s.split("\\")[-1] #输出为 class1.py

方法二:rfind
s=r"C:\Users\Desktop\lesson\python\calss1.py"
n=s.rfind("\\")#找到"\\"出现的位置
s[n+1:] #输出为 class1.py
s[:n] #输出为 'C:\\Users\\Desktop\\lesson\\python'

方法三:os.path.basename()  (推荐)
s='C:/Users/Desktop/lesson/python/calss1.py'
import os
os.path.dirname(s) #输出为 'C:/Users/Desktop/lesson/python'
os.path.basename(s) #输出为 class1.py

posted on   lshan  阅读(359)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2019-05-25 apollo docker 安装 使用官网镜像
2018-05-25 spring data jpa 原生查询(查一个json中的某一字段)
点击右上角即可分享
微信分享提示