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)
相关推荐
yiangL_几秒前
课后作业7:自动轨迹绘制
python
Wellijohn15 分钟前
async 里混进一行同步代码:事件循环卡死 4 秒,我写了个探针把它抓出来
后端·python·性能优化
JonaHu1 小时前
GPT Image 2.6 电商换背景如何公平对比:同源候选、匿名评审与返工统计
图像处理·人工智能·python·aigc
青少儿编程课堂1 小时前
蓝桥杯青少组图形化真题:校园无人机编队灯光秀解析(全国青少年信息素养大赛·电子学会12月图形化考级同源考点)
c++·python·算法·bfs·信息学竞赛
BK贝壳6 小时前
bool-hybrid-array 的 GPU_opt 与 cjx:一个没显卡就报错的开关,一个把 800 字压到 96 字节的编码
python
BD_Marathon10 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw10 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn11 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
Logintern0913 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_9679801114 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算