Python 遍历某文件夹下所有文件夹或文件

1、使用os库中的listdir方法

os.listdir(path) 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表(不包含子文件夹里的文件夹和文件)

os.path.isfile(path)判断路径是否为文件。os.path.isdir(path)判断路径是否为目录

os.path.join(path1, path2\[, ...])把目录和文件名合成一个路径

python 复制代码
import os
basepath=r'根文件夹'
rootpaths=os.listdir(basepath)
for rootpath in rootpaths[:]:
    if os.path.isfile(os.path.join(basepath,rootpath)):#移除文件
        rootpaths.remove(rootpath)

2、使用os库中的scandir方法

os.scandir(path)返回指定文件夹下文件夹和文件对应的os.DirEntry对象的迭代器(不包含子文件夹里的文件夹和文件),运行效率比os.walk高。

os.DirEntry.is_dir(),os.DirEntry对象的is_dir()方法用于检查路径是否为文件夹。

os.DirEntry.is_file(),os.DirEntry对象的is_file()方法用于检查路径是否为文件。

python 复制代码
import os
basepath=r'根文件夹'
rootpaths=os.scandir(basepath)
rootpaths_list=[]
files_list=[]
for rootpath in rootpaths:
    if item.is_dir():#判断该对象对应路径是否为文件夹
        rootpaths_list.append(item.path)
    elif item.is_file():#判断该对象对应路径是否为文件
        files_list.append(item.path)
相关推荐
点云-激光雷达-Slam-三维牙齿1 小时前
速度起飞 笔记本电脑6G显卡llama运行Qwen3.6 35BA3B MTP 大模型
人工智能·python·电脑·llama
言乐62 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
从零开始学习人工智能9 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
卷无止境10 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha131410 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教10 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教11 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
卷无止境11 小时前
FastAPI 的Admin面板生态
后端·python
ctlover11 小时前
Streamlit 框架
python
ι:12 小时前
MATLAB 与 Python 搭建无人机地面站:优势、劣势与选型逻辑
python·matlab·无人机