Python中os.walk用法详解

os.walk() 是 Python 中用于遍历目录树的强大函数。让我详细解释每个变量返回的信息和用法:

基本概念

  • root: 当前正在访问的目录路径
  • dirs: 当前目录下的子目录列表
  • files: 当前目录下的文件列表

示例目录结构

复制代码
project/
├── log_2024_01.txt
├── config.ini
├── logs/
│   ├── system.log
│   ├── app.log
│   └── archive/
│       └── old_log.txt
└── data/
    ├── input.csv
    └── output.csv

具体例子

python 复制代码
import os

# 假设当前目录结构如上所示
log_dir_path = "./project"

for root, dirs, files in os.walk(log_dir_path):
    print(f"当前目录: {root}")
    print(f"子目录列表: {dirs}")
    print(f"文件列表: {files}")
    print("-" * 50)

第一次迭代

复制代码
当前目录: ./project
子目录列表: ['logs', 'data']  # 当前目录下的子文件夹
文件列表: ['log_2024_01.txt', 'config.ini']  # 当前目录下的文件

第二次迭代

复制代码
当前目录: ./project/logs
子目录列表: ['archive']  # logs文件夹下的子目录
文件列表: ['system.log', 'app.log']  # logs文件夹下的文件

第三次迭代

复制代码
当前目录: ./project/logs/archive
子目录列表: []  # 没有子目录
文件列表: ['old_log.txt']  # archive文件夹下的文件

第四次迭代

复制代码
当前目录: ./project/data
子目录列表: []  # 没有子目录
文件列表: ['input.csv', 'output.csv']  # data文件夹下的文件

实际应用示例

1. 查找特定文件

python 复制代码
import os

for root, dirs, files in os.walk("."):
    for file in files:
        if file.endswith(".log"):
            full_path = os.path.join(root, file)
            print(f"找到日志文件: {full_path}")

2. 计算目录大小

python 复制代码
import os

total_size = 0
for root, dirs, files in os.walk("."):
    for file in files:
        file_path = os.path.join(root, file)
        total_size += os.path.getsize(file_path)

print(f"总大小: {total_size} 字节")

3. 遍历时排除特定目录

python 复制代码
import os

exclude_dirs = ['.git', '__pycache__', 'node_modules']

for root, dirs, files in os.walk("."):
    # 从 dirs 列表中移除要排除的目录
    dirs[:] = [d for d in dirs if d not in exclude_dirs]
    
    for file in files:
        print(os.path.join(root, file))

4. 获取所有文件的完整路径

python 复制代码
import os

all_files = []
for root, dirs, files in os.walk("/path/to/directory"):
    for file in files:
        full_path = os.path.join(root, file)
        all_files.append(full_path)

print(f"找到 {len(all_files)} 个文件")

重要特性

  1. 默认是深度优先遍历(从上到下)

  2. 可以控制遍历方向

    python 复制代码
    # 自顶向下遍历(默认)
    for root, dirs, files in os.walk(".", topdown=True):
        pass
    
    # 自底向上遍历
    for root, dirs, files in os.walk(".", topdown=False):
        pass
  3. 修改 dirs 会影响遍历

    python 复制代码
    for root, dirs, files in os.walk("."):
        # 不遍历隐藏目录
        dirs[:] = [d for d in dirs if not d.startswith('.')]

实际使用技巧

python 复制代码
import os

class LogProcessor:
    def __init__(self, log_dir_path):
        self.log_dir_path = log_dir_path
    
    def process_logs(self):
        for root, dirs, files in os.walk(self.log_dir_path):
            # 按日期处理日志
            for file in files:
                if file.endswith('.log'):
                    self._process_single_log(root, file)
    
    def _process_single_log(self, directory, filename):
        filepath = os.path.join(directory, filename)
        # 处理日志文件的逻辑
        print(f"处理: {filepath}")

# 使用示例
processor = LogProcessor("./logs")
processor.process_logs()

os.walk() 是一个非常实用的函数,特别适合需要递归处理文件系统的场景,比如日志分析、文件备份、批量重命名等任务。


相关推荐
Csvn1 天前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch89181 天前
Python主流框架全解析
开发语言·python
sg_knight1 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财1 天前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張4081 天前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533991 天前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz1 天前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据1 天前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby1 天前
springboot读取配置文件
后端·python·flask
阿Y加油吧1 天前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python