Python实现 Linux tree命令:用树形结构显示目录结构

在网上看了一篇 Linux tree命令的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, op):
		list = self.getList(dir, 0, op)
		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, op):
		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, op)
			elif op == '-d':
				pass
			else:
				list.append(file)
		return list

if len(sys.argv) < 2 :
	t = XXTree()
	t.printHelp(sys.argv[0])
else:
	t = XXTree()

	dir = None
	if len(sys.argv) == 2:
		dir = sys.argv[1]

	op = None
	if len(sys.argv) == 3:
		op = sys.argv[1]
		dir = sys.argv[2]

	t.getTree(dir, op)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值