Python学习笔记(2)——遍历目录结构并打印

有时候想看一下项目中的目录和文件结构,用python实现

主要用到这几个函数

import os

os.getcwd()  #获取当前运行程序的目录

os.listdir(path) #取得path下的文件和目录,返回值List类型

os.path.isdir(path) #判断path路径是否为目录

os.path.isfile(path)#判断path路径是否为文件

os.path.splitext(path)#对path路径切片,第二个为文件拓展名,例如'.py'

代码如下

import os

#只打印以下文件拓展名
cType = ['.py','.html','.css','.js','.sql']
def show_file(path,deep):
    #取得当前目录下的文件夹以及文件,返回值List类型
    file_list = os.listdir(path)
    #实现遍历目录
    for dir in file_list:
        if os.path.isdir(path+'/'+dir):
            if deep == 0:
                print dir+'/'
            else:
                print '| '*deep+'+-'+dir+'/'
            #递归打印
            show_file(path+'/'+dir,deep+1)
    #实现遍历文件
    for file in file_list:
        if os.path.isfile(path+'/'+file):
            #过滤文件
            for type in cType:
                #对路径切片获得文件拓展名
                if os.path.splitext(path+'/'+file)[1] == type:
                    if deep == 0:
                        print file
                    else:
                        print '| '*deep+'+-'+file
                    break;

if __name__ == '__main__':
    path = os.getcwd()
    print path
    show_file(path,0)

例如打印某一目录结构:
/web/mycode/python/learn_web
serving_xml/
| +-templates/
| +-code.py
| +-__init__.py
basic_blog/
| +-templates/
| | +-new.html
| | +-base.html
| | +-index.html
| | +-edit.html
| | +-view.html
| | +-login.html
| +-scheme.sql
| +-model.py
| +-blog.py
| +-__init__.py
todo_list/
| +-templates/
| | +-base.html
| | +-index.html
| | +-admin.html
| +-model.py
| +-schema.sql
| +-todo.py
| +-__init__.py

方法二:

# coding=utf-8
__author__ = 'nianyu'

from os.path import basename, isdir, exists
from os import listdir
from sys import argv


def show_tree(path,depth=0):
    print depth* '| ' + '|_', basename(path)
    if(isdir(path)):
        for item in listdir(path):
            show_tree(path+'/'+item, depth+1)


def isExist(path):
    if path[0] is not '/':
        return False

    if not exists(path):
        return False

    return True


if __name__ == "__main__":

    args = argv
    if len(args)>2:
        print "more than one argument."
        exit(0)

    path = str(args[1])
    if not isExist(path):
        print "the file path do not exist."
        exit(0)

    # show_tree("./")
    show_tree(path)



你可能感兴趣的:(Python学习笔记(2)——遍历目录结构并打印)