한양과학기술고등학교

에듀테크 프로젝트 대시보드

파일 입출력 · pathlib

open with pathlib encoding read/write

항상 with 로 열고, 텍스트 파일은 encoding="utf-8" 을 명시하세요.

1. 읽기

with open("data.txt", encoding="utf-8") as f:
    content = f.read()          # 전체를 문자열로
    # f.readlines()             # 줄 리스트 (\n 포함)

with open("data.txt", encoding="utf-8") as f:
    for line in f:              # 한 줄씩 (대용량 안전)
        print(line.rstrip())

2. 쓰기·추가

with open("out.txt", "w", encoding="utf-8") as f:
    f.write("한 줄\n")
    f.writelines([f"{i}\n" for i in range(3)])
    print("print 로도 가능", file=f)

with open("log.txt", "a", encoding="utf-8") as f:   # append
    f.write("추가 줄\n")

3. 파일 모드

모드의미
"r"읽기 (기본)
"w"쓰기 — 기존 내용 삭제
"a"이어쓰기
"x"새로 만들기 (있으면 에러)
"b"바이너리 ("rb", "wb")
"+"읽기+쓰기 ("r+")

4. pathlib — 경로 다루기

from pathlib import Path

p = Path("data") / "2024" / "log.txt"   # OS 무관 구분자
p.name          # 'log.txt'
p.stem          # 'log'
p.suffix        # '.txt'
p.parent        # Path('data/2024')
p.exists(); p.is_file(); p.is_dir()

p.read_text(encoding="utf-8")           # 간단 읽기
p.write_text("내용", encoding="utf-8")  # 간단 쓰기
Path("out").mkdir(parents=True, exist_ok=True)

5. 디렉터리 순회

from pathlib import Path
base = Path(".")

for f in base.iterdir():            # 바로 아래만
    print(f)
for py in base.glob("*.py"):        # 패턴
    print(py)
for py in base.rglob("*.py"):       # 재귀
    print(py)

import shutil
shutil.copy("a.txt", "b.txt")
shutil.rmtree("olddir")

6. 구조화된 파일

import json
with open("config.json", encoding="utf-8") as f:
    cfg = json.load(f)
with open("out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

import csv
with open("t.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"])
"특별한 경우라도 규칙을 어길 만큼 특별하지는 않다"