Make directory tree of sys.path from dict and list
我试图理解sys.path。
所以我想生成返回目录树的代码,但是我不能。
有人能告诉我密码吗?
路径系统
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | ['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)】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | {'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']}]} |
这是我能得到的最简单的。其想法是保持一组目前没有分歧的路径。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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)) |
这将为您提供一个字典,其中每个键都是一个目录,值是文件名或带有子目录的字典的列表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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) |
打印输出:
1 2 3 4 5 6 7 8 9 | runner/ .bashrc .bash_logout .profile .site-packages/ main.py .config/ pycodestyle _test_runner.py |
这是受到这个问题的启发,但我对实现做了很大的改变。