python 根据文件路径生成zTree插件需要的数据格式

python生成前端目录树zTree插件需要的数据格式
一、首先准备数据
     ll= ['/app/',
          '/nficd/test_app/htmlname.py',
          '/nficd/test_app/migrations/',
          '/nficd/test_app/migrations/models.py',
          '/nficd/test_app/migrations/sec_audit.log',
          '/nficd/test_app/templates/',
          '/nficd/test_app/templates/test_app/',
          '/nficd/test_app/templates/test_app/set.html',
          '/nficd/test_app/tests.py',
          '/nficd/test_app/urls.py',
          '/nficd/test_app/log.py',]
二、处理数据格式
1、按行处理数据,并将结果返回
代码:
if __name__ == '__main__':
    for l in ll:
        tree = test_1(l)
        current = test_3(tree, current)
        print(current)
返回值tree数据(随机一条):
[{'text': 'nficd', 'children': [{'text': 'test_app', 'children': [{'text': 'htmlname.py'}]}]}]
函数test_1():

    def test_1(l):
       isDir = False
       if l[-1] == '/':
           l_list = l[1:-1].split('/')
           isDir = True
       else:
           l_list = l[1:].split('/')
       return test_2([], l_list, isDir)
函数test_2():

	def test_2(list, l_list, isDir):
	    if not isDir and len(l_list) == 1:
	        list.append({"text": l_list[0]})
	        l_list.remove(l_list[0])
	        return list
	    for ls in l_list:
	        x1 = []
	        list.append({"text": ls, "children": x1})
	        l_list.remove(ls)
	        test_2(x1, l_list, isDir)
	    return list
2、将1中的每行结果处理,写入到list数组中
上面提到的代码:current = test_3(tree, current)
函数test_3():
	def test_3(tree, current):
	    if len(tree) > 0 and len(current) == 0:
	        current.append(tree[0])
	    else:
	        text = tree[0]['text']
	        key_exist = [i['text'] for i in current]
	        if text not in key_exist:
	            current.append(tree[0])
	        else:
	            index = key_exist.index(text)
	            test_3(tree[0]["children"], current[index]["children"])
	    return current
上面结尾:print(current)
格式化输出结果:
    [{
   	'text': 'app',
   	'children': []
   }, {
   	'text': 'nficd',
   	'children': [{
   		'text': 'test_app',
   		'children': [{
   			'text': 'htmlname.py'
   		}, {
   			'text': 'migrations',
   			'children': [{
   				'text': 'models.py'
   			}, {
   				'text': 'sec_audit.log'
   			}]
   		}, {
   			'text': 'templates',
   			'children': [{
   				'text': 'test_app',
   				'children': [{
   					'text': 'set.html'
   				}]
   			}]
   		}, {
   			'text': 'tests.py'
   		}, {
   			'text': 'urls.py'
   		}, {
   			'text': 'log.py'
   		}]
   	}]
   }]
这里进行了格式化,代码里面并没有实现

代码不够美观,也肯定有更好的方法,主要是自己写的,记录一下,如果有更好的,请告诉我,学习学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值