파이썬 yaml 다루는 방법

yaml

YAML은 사람도 읽기 쉽고, 기계도 파싱하기 쉬운 데이터 직렬화 포맷입니다.

주로 설정 파일(config file)이나 데이터 정의 등에 많이 사용되며,

특히 Python 프로젝트나 서버 설정, Kubernetes, GitHub Actions 같은 환경에서 자주 등장합니다.

 

YAML 예제

config.yaml

name: TopProject
project:
  title: AI Transformation
  year: 2025
members:
  - name: Kim
    role: Manager
  - name: Lee
    role: Developer

 

YAML 읽기

보안상 안전하게 yaml 을 파싱할 때는 safe_load() 를 사용 합니다. 

 

import yaml

with open('config.yaml', 'r', encoding="utf-8") as file:
    try:
    	data = yaml.safe_load(file)
    except yaml.YAMLError as exc:
    	raise ValueError(f"YAML file {yaml_path} could not be loaded.") from exc

print(data)
{
  'name': 'TopProject',
  'project': {'title': 'AI Transformation', 'year': 2025},
  'members': [
    {'name': 'Kim', 'role': 'Manager'},
    {'name': 'Lee', 'role': 'Developer'}
  ]
}
반응형