python 中 os.walk() 函数详解

Posted on   风行天下-2080  阅读(394)  评论(0编辑  收藏  举报

1、

https://www.jb51.net/article/226935.htm

https://www.runoob.com/python/os-walk.html

https://www.cnblogs.com/he-ding/p/10045246.html

os.walk()是一种遍历目录数的函数,它以一种深度优先的策略(depth-first)访问指定的目录。这篇文章主要介绍了python 中 os.walk() 函数,需要的朋友可以参考下
 

os.walk()是一种遍历目录数的函数,它以一种深度优先的策略(depth-first)访问指定的目录。

其返回的是(root,dirs, files),

  • root代表当前遍历的目录路径,string类型
  • dirs代表root路径下的所有子目录名称,list类型,列表中的每个元素是string类型,代表子目录名称。
  • files代表root路径下的所有子文件名称,返回list类型,列表中的每个元素是string类型,代表子文件名称。

加入我当前的目录如下。

在这里插入图片描述

可以先打印一下其是怎么遍历的:

1
2
3
4
5
6
7
8
9
import os
from os.path import join
 
home_path = "/home"
for (root, dirs, files) in os.walk(home_path):
    print(root)
    print(dirs)
    print(files)
    print("=" * 50)

输出如下:

 

/home
['root', 'zhang', 'li']
['test.txt', 'hai.mp4']
==================================================
/home/root
[]
['1.txt', '2.txt', '3.txt']
==================================================
/hoome/zhang
[]
['zhang_1.mp4', 'zhang_2.mp4', 'zhang_3.mp4']
==================================================
/home/li
[]
[]
==================================================

一共三行,
第1行代表当前遍历的目录,我们称为root目录,
第2行代表root目录下的子目录列表,我们称为dirs,
第3行代表root目录下的子文件列表,我们称为files,
上面的列表为空就代表当前遍历的root目录下没有子目录或者没有子文件

另外,如果我想遍历home目录下所有的目录和文件的绝对路径,则直接用os.path.join()方法对 子目录或子文件名root目录 进行拼接即可,则代码如下:

1
2
3
4
5
6
7
8
9
import os
from os.path import join
 
home_path = "/home"
for (root, dirs, files) in os.walk(home_path):
    for dir in dirs:
        print(join(root, dir))
    for file in files:
        print(join(root, file))

输出:

/home
/home/root
/home/zhang
/home/li
/home/test.txt
/home/hai.mp4
/home/root/1.txt
/home/root/2.txt
/home/root/3.txt
/home/zhang/zhang_1.mp4
/home/zhang/zhang_2.mp4
/home/zhang/zhang_3.mp4

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2019-09-09 python相关cmdb系统

随笔 - 618, 文章 - 0, 评论 - 6, 阅读 - 37万

Copyright © 2025 风行天下-2080
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示