300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > Linux用树形结构显示目录结构

Linux用树形结构显示目录结构

时间:2019-09-24 06:02:19

相关推荐

Linux用树形结构显示目录结构

在有些Linux上自带了tree命令来一树状结构显示一个目录,但是在有些linux上没有自带这个程序,所以这里用python写了一个小程序来实现这个功能,代码如下:

#!/usr/bin/python import os, sys, string class XXTree: def __init__(self): pass def printHelp(self, cmd): print 'Please use the following cmd:' print ' ' + cmd + ' dir' print 'e.g.' print ' ' + cmd + ' /home/fkong/tmp' def getTree(self, dir): list = self.getList(dir, 0) treelist = [] for i in range(0, len(list)): fullpath = list[i] parpath = os.path.dirname(list[i]) filename = os.path.basename(list[i]) if(fullpath == dir): treelist.append(fullpath) continue path = fullpath.replace(dir, "") names = path.split("/") name = "`---" + names[len(names) - 1] for j in range(1, len(names) - 1): name = " " + name treelist.append(name) pos = name.index("`") j = i - 1 while j > 0: name = treelist[j] if(name[pos] == '`' or name[pos] == ' '): name = name[0: pos] + "|" + name[pos + 1: len(name)] treelist[j] = name else: break j = j - 1 for i in range(0, len(treelist)): print treelist[i] def getList(self, dir, layer): list = [] if layer == 0: list.append(dir) files = os.listdir(dir) for file in files: file = os.path.join(dir, file) if os.path.isdir(file): list.append(file) list += self.getList(file, layer + 1) else : list.append(file) return list if len(sys.argv) != 2: t = XXTree() t.printHelp(sys.argv[0]) else: t = XXTree() dir = sys.argv[1] t.getTree(dir)

运行效果如下:

$ ./xxtree.py /home/fkong/workspace/jutility/.svn

/home/fkong/workspace/jutility/.svn

|---format

|---props

|---entries

|---prop-base

|---text-base

|---tmp

| |---prop-base

| |---props

| `---text-base

`---all-wcprops

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。