当前位置:编程学习 > 网站相关 >>

python遍历目录

#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
python遍历目录
http://laocao.blog.51cto.com/480714/525140
'''

import os

#输出总是先文件夹后文件名的
def Test1(rootDir): 
    list_dirs = os.walk(rootDir)
    for root, dirs, files in list_dirs: 
        for d in dirs: 
            print os.path.join(root, d)      
        for f in files:
            print os.path.join(root, f)

#按照目录树结构以及按照首字母排序进行输出的
def Test2(rootDir): 
    for lists in os.listdir(rootDir): 
        path = os.path.join(rootDir, lists) 
        print path 
        if os.path.isdir(path): 
            Test2(path)
            
    
    
if __name__ == '__main__':
    Test1('C://Intel')
    Test2('C:\Intel')



补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,