从字典和列表中创建sys.path的目录树

时间:2019-02-24 06:34:29

标签: python

我试图了解sys.path。

所以我想制作返回这样的目录树的代码,但我做不到。

有人可以告诉我代码吗?

【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']

【目录树(字典)】

{'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']}]}

2 个答案:

答案 0 :(得分:0)

这将为您提供一个字典,其中每个键都是目录,而值是文件名或带有子目录的词典的列表。

cloud functions onUpdate

打印输出:

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)

这受this SO issue的启发,但是我对实现做了很多更改。

答案 1 :(得分:0)

这是我能获得的最简单的方法。这个想法是要维护一组目前没有分歧​​的路径。

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))