[파이썬] shutil 디렉토리 구조를 JSON 또는 XML로 내보내기

파이썬에서 shutil 모듈은 파일 및 디렉토리 작업을 수행하는 데 사용되는 강력한 도구입니다. 이 모듈은 디렉토리를 복사, 이동, 삭제하는 데 도움을 주며, 파일을 압축하거나 해제하는 등의 작업도 수행할 수 있습니다.

작업 중인 디렉토리 구조를 다른 프로그램이나 시스템과 공유하기 위해 JSON 또는 XML로 내보내는 것은 유용한 작업입니다. 이러한 내보내기 작업을 수행하는 방법을 알아보겠습니다.

JSON로 디렉토리 구조 내보내기

내보내기할 디렉토리 구조를 포함하는 함수를 만들어 보겠습니다. 이 함수는 주어진 디렉토리를 검사하고 하위 파일 및 디렉토리를 재귀적으로 탐색하면서 JSON 객체를 생성합니다.

import os
import json

def export_directory_structure_to_json(path, output_file):
    if not os.path.exists(path):
        raise Exception("Invalid path")

    data = {}
    data["name"] = os.path.basename(path)
    data["type"] = "dir"
    data["contents"] = []

    for name in os.listdir(path):
        sub_path = os.path.join(path, name)
        if os.path.isdir(sub_path):
            data["contents"].append(export_directory_structure_to_json(sub_path, output_file))
        else:
            file_data = {}
            file_data["name"] = name
            file_data["type"] = "file"
            data["contents"].append(file_data)

    with open(output_file, "w") as file:
        json.dump(data, file, indent=4)

위의 함수는 path 매개 변수로 지정된 디렉토리의 내부 구조를 생성하고, output_file 매개 변수로 지정된 파일에 JSON 형식으로 저장합니다.

XML로 디렉토리 구조 내보내기

XML로 디렉토리 구조를 내보내는 방법은 다소 다릅니다. 우리는 xml.etree.ElementTree 모듈을 사용하여 XML 출력을 생성할 것입니다. 다음은 XML로 디렉토리 구조를 내보내기 위한 예제 코드입니다.

import os
import xml.etree.ElementTree as ET

def export_directory_structure_to_xml(path, output_file):
    if not os.path.exists(path):
        raise Exception("Invalid path")

    root = ET.Element("directory")
    root.set("name", os.path.basename(path))

    for name in os.listdir(path):
        sub_path = os.path.join(path, name)
        if os.path.isdir(sub_path):
            subdir_element = export_directory_structure_to_xml(sub_path, output_file)
            root.append(subdir_element)
        else:
            file_element = ET.SubElement(root, "file")
            file_element.set("name", name)

    tree = ET.ElementTree(root)
    tree.write(output_file)

위의 함수는 path 매개 변수로 지정된 디렉토리의 내부 구조를 생성하고, output_file 매개 변수로 지정된 파일에 XML 형식으로 저장합니다.

사용 예제

이제 위에서 정의한 함수를 사용하여 디렉토리 구조를 JSON 또는 XML로 내보내는 방법을 알아보겠습니다.

# JSON으로 내보내기
export_directory_structure_to_json("/path/to/directory", "directory_structure.json")

# XML로 내보내기
export_directory_structure_to_xml("/path/to/directory", "directory_structure.xml")

위의 코드에서 /path/to/directory를 내보내고자 하는 실제 디렉토리 경로로 변경해야 합니다. 내보내기를 실행한 후 지정된 파일(directory_structure.json 또는 directory_structure.xml)을 열어 내보낸 디렉토리 구조를 확인할 수 있습니다.

이렇게하면 shutil 모듈을 사용하여 디렉토리 구조를 JSON 또는 XML로 내보낼 수 있습니다. 이러한 기능을 사용하면 데이터를 쉽게 사용 가능한 형식으로 공유하고 다른 시스템에서 처리할 수 있습니다.