2014-10-09 2 views
2

현재 작업하고있는 프로젝트와 파일을 보유하고있는 JSON 구조체를 저장하고 싶습니다. 파일 구조는 다음과 같습니다Python의 디렉토리 구조에 JSON 렌더링하기

|-project1 
|--sequence1 
|----file1.ext 
|----file2.ext 
|-project2 
|--sequence1 
|----file1.ext 
|----file2.ext 
|-project3 
|--sequence3 
|----file1.ext 
|----file2.ext 

JSON 버전은 다음과 같을 것이다 :

data = [ 
    { 
    type: "folder", 
    name: "project1", 
    path: "/project1", 
    children: [ 
     { 
     type: "folder", 
     name: "sequence1", 
     path: "/project1/sequence1", 
     children: [ 
      { 
      type: "file", 
      name: "file1.ext", 
      path: "/project1/sequence1/file1.ext" 
      } , { 
      type: "file", 
      name: "file2.ext", 
      path: "/project1/sequence1/file2.ext" 

      ...etc 
      } 
     ] 
     } 
    ] 
    } 
] 

는 파이썬을 사용하여 실제 디렉토리와 파일에이 구조를 렌더링 할 수 있습니까? (빈 파일 일 수 있습니다). 다른 한편으로는, 기존의 디렉토리를 횡단하는 함수를 작성해, 유사한 JSON 코드를 돌려주고 싶습니다.

+0

'json'모듈 (표준 라이브러리의 일부)과 'load'또는 'loads'함수를 사용하여 파일이나 문자열에서 파이썬 사전으로 데이터를로드 할 수 있습니다. –

답변

1

이 재귀 함수와 os 모듈의 케이크의 일부를 사용하여 사전을 만들 수있을만큼 쉽게해야 ... :

import os 

def dir_to_list(dirname, path=os.path.pathsep): 
    data = [] 
    for name in os.listdir(dirname): 
     dct = {} 
     dct['name'] = name 
     dct['path'] = path + name 

     full_path = os.path.join(dirname, name) 
     if os.path.isfile(fullpath): 
      dct['type'] = 'file' 
     elif os.path.isdir(fullpath): 
      dct['type'] = 'folder' 
      dct['children'] = dir_to_list(full_path, path=path + name + os.path.pathsep) 
    return data 

검증되지 않은

그럼 그냥 수 파일에 json.dump 또는 문자열에 json.dumps입니다. . .

관련 문제