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)
相关推荐
hboot5 小时前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780519 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户83562907805111 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠17 小时前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz31017 小时前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫17 小时前
python环境|conda安装和使用(2)
后端·python
程序员龙叔1 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780511 天前
使用 Python 操作 Word 内容控件
后端·python
码云骑士1 天前
32-慢查询排查全流程(下)-索引优化实战与最左前缀原则
python