Python 기초 실습 C5

Python 기초 실습 C5입니다. pathlib 기반 파일 입출력, JSON 저장/읽기, ensure_ascii=False, 예외 처리와 실행 테스트를 정리했습니다.

Python 기초 실습 C5

C5 실습은 파일 입출력과 JSON 저장을 다룬다. 콘솔에서 입력받은 데이터를 메모리에만 두면 프로그램이 종료될 때 사라진다. 파일로 저장하고 다시 읽는 흐름을 익히면 이후 Flask나 자동화 스크립트에서 설정 파일, 로그, 간단한 데이터 저장을 다루기 쉬워진다.

프로젝트 구조

python-c5/
├── main.py
└── data/
    └── notes.json

디렉터리 준비

mkdir -p python-c5/data
cd python-c5

main.py

pathlib.Path를 사용하면 운영체제별 경로 차이를 덜 신경 써도 된다. json.dumps에는 ensure_ascii=False를 넣어야 한글이 사람이 읽기 좋게 저장된다.

import json
from pathlib import Path

DATA_FILE = Path("data/notes.json")


def load_notes() -> list[dict]:
    if not DATA_FILE.exists():
        return []
    return json.loads(DATA_FILE.read_text(encoding="utf-8"))


def save_notes(notes: list[dict]) -> None:
    DATA_FILE.parent.mkdir(parents=True, exist_ok=True)
    DATA_FILE.write_text(
        json.dumps(notes, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )


def add_note(title: str, body: str) -> None:
    notes = load_notes()
    next_id = max((note["id"] for note in notes), default=0) + 1
    notes.append({"id": next_id, "title": title, "body": body})
    save_notes(notes)


def print_notes() -> None:
    for note in load_notes():
        print(f'{note["id"]}. {note["title"]} - {note["body"]}')


if __name__ == "__main__":
    add_note("Python C5", "파일 입출력과 JSON 저장 실습")
    add_note("Next", "Flask에서 파일 데이터를 읽어 화면에 출력")
    print_notes()

실행

python main.py
cat data/notes.json

예외 처리 추가

파일이 깨졌을 때 프로그램이 바로 죽지 않게 하려면 JSON 파싱 오류를 따로 처리한다.

def load_notes_safe() -> list[dict]:
    if not DATA_FILE.exists():
        return []
    try:
        return json.loads(DATA_FILE.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        raise RuntimeError(f"invalid json file: {DATA_FILE}") from exc

정리

  • Path.read_text(), Path.write_text()로 파일을 읽고 쓴다.
  • 데이터 구조를 저장할 때는 JSON을 사용하면 다음 단계에서 재사용하기 좋다.
  • 한글 저장에는 UTF-8과 ensure_ascii=False를 명시한다.
  • 파일이 없는 경우와 파일이 깨진 경우를 구분해서 처리한다.
BGM EVER