- 여러 주피터 노트북을 하나로 병합하는 파이썬 코드
import os
import json
from datetime import datetime
def get_files(folder: str) -> list[str]:
"""
주피터 노트북 파일 이름순으로 정렬
Args:
folder (str): 주피터 노트북 파일 폴더 경로
Returns:
list[str]: 정렬된 주피터 노트북 파일 이름 리스트
"""
notebooks = [
file.name for file in os.scandir(folder)
if file.is_file() and file.name.endswith('.ipynb')
]
notebooks.sort()
return notebooks
def load_notebook(file_path: str) -> dict:
"""
주피터 노트북 JSON 형식으로 반환
Args:
file_path (str): 주피터 노트북 파일 경로
Returns:
dict: 주피터 노트북 JSON 객체
"""
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
def merge_notebooks(folder: str, notebooks: list[str], output_path: str) -> None:
"""
여러 주피터 노트북 파일을 하나로 병합
Args:
folder (str): 주피터 노트북 파일 폴더 경로
notebooks (list[str]): 병합할 주피터 노트북 파일 이름 리스트
output_path (str): 병합된 결과를 저장할 경로
Returns:
None
"""
base = load_notebook(os.path.join(folder, notebooks[0]))
for notebook in notebooks[1:]:
nb_data = load_notebook(os.path.join(folder, notebook))
base['cells'].extend(nb_data['cells'])
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(base, f)
def timestamp_string() -> str:
"""파일 이름용 타임스탬프 문자열 반환"""
return datetime.now().strftime('%Y_%m_%d__%H_%M_%S')
if __name__ == "__main__":
IPYNB_FOLDER = '/content/drive/MyDrive/Colab Notebooks/ADP'
OUTPUT_FILENAME = 'merge.ipynb'
notebooks = get_files(IPYNB_FOLDER)
timestamp = timestamp_string()
output_filename = f"{timestamp}_{OUTPUT_FILENAME}"
output_path = os.path.join(IPYNB_FOLDER, output_filename)
merge_notebooks(IPYNB_FOLDER, notebooks, output_path)