python3实现linux命令tree

作者: jaket5219999 2017-01-18 09:57:58

system:centos6.7、Python -V:3.5.2


用递归的方法遍历文件和文件夹,并统计他们的个数。


后带的参数看查看子文件夹或绝对路径的树形结构图,省略后带参数则查看当前文件夹。


 


#!/usr/bin/env python3  


import os  


import sys  


from os.path import join,basename,isdir  


def tree(d,leval=0,pre=''):     


global a,b   


l=[i for i in os.listdir(d) if i[0]!='.']  


for i,f in enumerate(l):  


last= i==len(l)-1  


s1="'" if last else '|'  


s2=" " if last else '|'  


print('{}{}--{}'.format(pre,s1,f))          


t=join(d,f)  


if os.path.isdir(t):  


a+=1  


tree(t,leval+1,'{}{}  '.format(pre,s2))              


else:  


b+=1    


def main(d=os.getcwd()):                


print(basename(d.rstrip(os.sep)))  


tree(d)  


print('\ntotal={}folders,{}files\n'.format(a,b))  


if __name__=='__main__':  


a,b=0,0     #a,b分别为文件夹总数和文件总数  


if len(sys.argv)<2:  


main()  


else:  


if isdir(sys.argv[1]):  


main(sys.argv[1])  


else:  


print(sys.argv[1],'is not a directory')


 


运行结果:


[willie@localhost blog]$ python3 ~/code/tree.py  




[willie@localhost blog]$ python3 ~/code/tree.py templates/




 


PS:centos系统下超级用户执行:#yum -y install tree


就可以安装tree命令,其效果看起来确实更加美观。


 


本文永久更新地址:http://www.linuxdiyf.com/linux/27911.html

相关资讯