存档

文章标签 ‘order’

Python列出目录树并实现排序

2010年3月11日 没有评论

指定目录排序列出目录树并写入文件中

#! /usr/bin/env python
 
import os
import sys
 
def list_and_sort( path ):
    dirs = sorted([d for d in os.listdir(path) if os.path.isdir(path + os.path.sep + d)])
    dirs.extend(sorted([f for f in os.listdir(path) if os.path.isfile(path + os.path.sep + f)]))
    return dirs;
 
def listdir(space, dir,file):
    if space == '':
        file.write(dir + '\n' )
    prev = space
#list = os.listdir(dir)
    list = list_and_sort( dir )
    for line in list:
        filepath = os.path.join(dir,line)
        if os.path.isdir(filepath):
            if line.find( '.svn' ) >= 0:
                continue
            space = prev + '--'
            file.write( space + line + '\n' )
            listdir( space, filepath, myfile )
        elif os.path:
            ext = os.path.splitext(os.path.join(line) )[1].lower()
            if ext == '.o':
                continue
            space = prev + '--'
            myfile.write( space + line + '\n' )
 
dir = raw_input('please input the path:')
myfile = open('filelist.txt','w')
listdir( '', dir, myfile )
分类: 开发技术 标签: , ,