[英]Make directory tree of sys.path from dict and list
我正在尝试了解 sys.path。
所以我想制作像这样返回目录树的代码,但我不能。
有人可以告诉我代码吗?
【系统路径】
['C:\\Users\\81802\\PycharmProjects\\PlayGround',
'C:\\Users\\81802\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip',
'C:\\Users\\81802\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
'C:\\Users\\81802\\AppData\\Local\\Programs\\Python\\Python37\\lib',
'C:\\Users\\81802\\AppData\\Local\\Programs\\Python\\Python37',
'C:\\Users\\81802\\PycharmProjects\\PlayGround\\venv',
'C:\\Users\\81802\\PycharmProjects\\PlayGround\\venv\\lib\\site-packages',
'C:\\Users\\81802\\PycharmProjects\\PlayGround\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.7.egg',
'C:\\Users\\81802\\PycharmProjects\\PlayGround\\venv\\lib\\site-packages\\pip-10.0.1-py3.7.egg']
【目录树(dict)】
{'C:\\Users\\81802\\':
[{'PycharmProjects\\PlayGround\\':
['',
{'venv\\':
['',
{'lib\\site-packages\\':
['',
'setuptools-39.1.0-py3.7.egg',
'pip-10.0.1-py3.7.egg']}]}]},
{'AppData\\Local\\Programs\\Python\\Python37\\':
['',
'python37.zip',
'DLLs',
'lib']}]}
这将为您提供一个字典,其中每个键都是一个目录,值是文件名或带有子目录的字典的列表。
import os
def get_files_dict(startpath):
tree = [] # this is the array of subdirectory objects
for item in os.listdir(startpath):
# we need to have a full path to the item in the directory
item_path = os.path.join(startpath, item)
if os.path.isfile(item_path):
tree.append(item)
else:
# we call this function recursively for subdirectories
tree.append(get_files_dict(item_path))
return {os.path.basename(startpath):tree}
file_tree = get_files_dict(os.getcwd())
# this is just a helper function to print the tree nicely
def print_tree(d,i=0):
for k,v in d.items():
print("{}{}".format(" "*4*i, k+os.sep))
for l in v:
if type(l) is dict:
print_tree(l,i+1)
else:
print("{}{}".format(" "*4*(i+1), l))
print_tree(file_tree)
和打印输出:
runner/
.bashrc
.bash_logout
.profile
.site-packages/
main.py
.config/
pycodestyle
_test_runner.py
这是受此SO issue 的启发,但我对实现进行了相当多的更改。
这是我能得到的最简单的。 这个想法是维护一组当前没有发散的路径。
import sys
from pprint import pprint
pprint(sys.path)
sep = '\\'
# check if all paths agree on the current name
def isSameName(paths, index):
for path in paths:
if index >= len(path) or path[index] != paths[0][index]:
return False
return True
#transform the current set of paths into tree
def toTree(paths, startIndex):
index = startIndex
if len(paths) == 1:
return sep.join(paths[0][index:])
while isSameName(paths, index):
index += 1
nameMap = dict()
for path in paths:
name = path[index] if len(path) > index else 0
if not (name in nameMap):
nameMap[name] = []
nameMap[name].append(path)
res = [toTree(paths, index) for paths in nameMap.values()]
return { sep.join(paths[0][startIndex:index]) : res}
paths = [path.split(sep) for path in sys.path]
pprint(toTree(paths, 0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.