---
title: "python小例子之1 -- 递归遍历目录"
author: "weistar"
date: "2014-03-18T16:58:10Z"
tags: []
categories: ["编程语言"]
slug: "python-1"
draft: true
lastmod: "2014-03-18T16:58:10Z"
id: 2032923
url: "https://weistar.iteye.com/blog/2032923"
---

文章源自：http://bluecrystal.iteye.com/blog/116670

### python小例子之1 -- 递归遍历目录

        主题： 递归遍历目录  
        环境： winxp pro + sp2 + python2.5  
        备注： 请注意，凡是在源代码文件中使用了中文字符，请最好保存为utf-8格式  
        代码：

```
    #listdir.py
    import os  
    # 递归遍历指定的目录  
    # level -- 递归的层数，用这个参数来控制打印的缩进  
    # path  == 遍历起始绝对路径  
    def listyoudir(level, path):  
        for i in os.listdir(path):  
            print '  '*(level+1) + i  
            if os.path.isdir(path + os.path.sep + i):  
                listyoudir(level+1, path + os.path.sep + i)  
              
    #测试代码  
    rootpath = os.path.abspath('.')  
    print rootpath  
    listyoudir(0, rootpath)  
```