본문 바로가기
C.W.K.
Stream
Lesson 01 of 06 · published

open — 파일 모드와 안전한 수명

~20 min · open, file, mode, encoding

Level 0호기심
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

모드는 무엇을 하고 무엇을 돌려받는지 정해

r은 읽기, w는 기존 내용을 비우고 쓰기, a는 뒤에 붙이기, x는 새 파일만 만들기야. +는 읽기와 쓰기를 함께 허용하고, t는 글자, b는 바이트를 다뤄.

파일의 수명은 with로 묶어

직접 close를 마지막 줄에 두면 중간 예외에서 닫히지 않을 수 있어. with open(...)은 어떤 경로로 블록을 나가도 닫아.

인코딩과 보존은 별도 계약이야

텍스트 파일은 실제 인코딩을 명시해. 양쪽을 통제한다면 UTF-8이 좋은 기본값이야. 중요한 파일에 w로 바로 쓰면 여는 순간 원본이 사라질 수 있으니 같은 디렉터리의 임시 파일에 완성한 뒤 flush하고 원자적으로 바꿔.

Code

텍스트 파일 읽기와 쓰기·python
# 파일 통째 읽기
with open("/etc/hostname", encoding="utf-8") as f:
    content = f.read()
print(content.strip())

# 쓰기 — overwrite
with open("/tmp/out.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")
    f.write("world\n")

# Append
with open("/tmp/out.txt", "a", encoding="utf-8") as f:
    f.write("more\n")

# 생성-only — 있으면 실패
try:
    with open("/tmp/out.txt", "x", encoding="utf-8") as f:
        f.write("여기까지 안 옴")
except FileExistsError as e:
    print("이미 존재:", e)
파일을 줄 단위로 읽기·python
# 큰 파일에는 이 방식을 쓰지 마
# data = open("big.log", encoding="utf-8").read()      # 전부 로드

# 이거 — file 객체가 줄 단위로 iterable
with open("/tmp/out.txt", encoding="utf-8") as f:
    for line in f:
        print("got:", line.rstrip("\n"))

# .readlines() — 줄 list, eager
with open("/tmp/out.txt", encoding="utf-8") as f:
    lines = f.readlines()
    print(lines)              # ['hello\n', 'world\n', 'more\n']
바이너리 모드에서 bytes 다루기·python
# 바이너리 파일 읽기
with open("/bin/ls", "rb") as f:
    header = f.read(4)
print(header)                  # b'\x7fELF' on Linux/macOS

# 바이트 쓰기
with open("/tmp/raw.bin", "wb") as f:
    f.write(b"\xDE\xAD\xBE\xEF")

# 텍스트와 바이너리는 다른 파일 모드
try:
    with open("/tmp/raw.bin", "r") as f:    # 텍스트 모드!
        f.read()                              # UnicodeDecodeError 가능
except UnicodeDecodeError as e:
    print("예상대로:", e)
seek와 tell로 위치 옮기기·python
# 파일 안 seek 하려면 read+write 로 열기
with open("/tmp/seek.txt", "w+", encoding="utf-8") as f:
    f.write("hello world")
    print("위치:", f.tell())          # 11
    f.seek(0)
    print(f.read(5))                      # 'hello'
    f.seek(6)
    print(f.read())                       # 'world'

# 멀티바이트 컨텐츠에 정확한 byte seeking 은 바이너리 모드 필요
텍스트 인코딩을 명시하기·python
# Linux 에선 작동, Windows 시스템 locale 이 UTF-8 안 만들면 깨질 수 있음
# with open("data.txt") as f:
#     contents = f.read()

# 항상 인코딩 지정
with open("/tmp/out.txt", encoding="utf-8") as f:
    contents = f.read()
print(contents[:50])

# 3.11+ 가 명시적 'locale 사용' 위해 "locale" 추가 — 디폴트와 다름
# with open("data.txt", encoding="locale") as f: ...

External links

Exercise

/tmp/quest_test.txt에 UTF-8로 세 줄을 쓰고, 줄 번호와 함께 다시 읽은 뒤 네 번째 줄을 추가해. 모든 열기는 with를 쓰고 마지막에 네 줄이 모두 남았는지 확인해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.