遍历目录树返回字典树,目录字典

Posted similarface

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了遍历目录树返回字典树,目录字典相关的知识,希望对你有一定的参考价值。

  def getDirectoryTree(self,folder):
\'\'\'
:param folder:文件目录
:return:目录的字典
\'\'\'
dirtree={\'children\':[]}
if os.path.isfile(folder):
return {\'text\':os.path.basename(folder),\'icon\':\'glyphicon glyphicon-leaf\'}
else:
basename=os.path.basename(folder)
dirtree[\'text\']=basename
for item in os.listdir(folder):
dirtree[\'children\'].append(self.getDirectoryTree(os.path.join(folder,item)))
return dirtree

def getDirectoryTreeWithJson(self,folder):
\'\'\'
将文件夹生成树状的json串
:param folder: 文件夹
:return:文件树json
\'\'\'
return json.dumps(self.getDirectoryTree(folder))

 result:

{\'text\': \'\', \'children\': [{\'text\': \'1\', \'icon\': \'glyphicon glyphicon-leaf\'}, {\'text\': \'2\', \'icon\': \'glyphicon glyphicon-leaf\'}, {\'text\': \'child01\', \'children\': [{\'text\': \'child001\', \'children\': []}]}, {\'text\': \'child02\', \'children\': []}]}

 网页展示:

<!DOCTYPE html>
<html class=""> <!--<![endif]-->
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>jsTree</title>
	<meta name="viewport" content="width=device-width" />
	<!--[if lt IE 9]><script src="./assets/html5.js"></script><![endif]-->
	
	<meta name="robots" content="index,follow" />
	<link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css" />
	<!--控制字体的样式的-->
	<link rel="stylesheet" href="./assets/dist/themes/default/style.min.css" />
	<!-- 背景的样式下面这行 -->
	<!-- <link rel="stylesheet" href="./assets/docs.css" /> -->
	<!--[if lt IE 9]><script src="./assets/respond.js"></script><![endif]-->
	
	<link rel="icon" href="./assets/favicon.ico" type="image/x-icon" />
	<link rel="apple-touch-icon-precomposed" href="./assets/apple-touch-icon-precomposed.png" />
	<script>window.$q=[];window.$=window.jQuery=function(a){window.$q.push(a);};</script>
</head>
<body>
	<div>
		<div id="jstree2" class="" style="margin-top:2em;"></div>
		<script>
		$(function () {
			$(\'#jstree1\').jstree();
			$(\'#jstree2\').jstree({\'plugins\':["wholerow","checkbox"], \'core\' : {
				\'data\' : [
					{\'text\': \'temp\', \'children\': [{\'text\': \'1\', \'icon\': \'glyphicon glyphicon-leaf\'}, {\'text\': \'2\', \'icon\': \'glyphicon glyphicon-leaf\'}, {\'text\': \'child01\', \'children\': [{\'text\': \'child001\', \'children\': []}]}, {\'text\': \'child02\', \'children\': []}]}
,
					"And wholerow selection"
				]
			}});
		});
		</script>
	</div>
	<script src="./assets/jquery-1.10.2.min.js"></script>
	<script src="./assets/jquery.address-1.6.js"></script>
	<script src="./assets/vakata.js"></script>
	<script src="./assets/dist/jstree.min.js"></script>
	<script src="./assets/docs.js"></script>
	<script>$.each($q,function(i,f){$(f)});$q=null;</script>
</body>
</html>

结果:

  

 

以上是关于遍历目录树返回字典树,目录字典的主要内容,如果未能解决你的问题,请参考以下文章

字典树(java)

字典树目录

Aho-Corasick automaton

字典树

前缀树(字典树/Trie) -----Java实现

字典树入门(trie)(概念+例题)