포스트

[Python 100일 챌린지] Day 41 - 파일 입출력 기초

[Python 100일 챌린지] Day 41 - 파일 입출력 기초

Phase 5 시작! 🎉 open('memo.txt', 'w') → 파일이 생긴다!

프로그램 종료 후에도 남아있는 메모장, 게임 저장 파일, 사용자 설정… 변수는 프로그램 끄면 사라지지만, 파일은 영구 저장됩니다! 😊

(30-40분 완독 ⭐⭐⭐)

🎯 오늘의 학습 목표

⭐⭐⭐ (30-40분 완독)

📚 사전 지식


🎯 학습 목표 1: 파일 입출력 기초 이해하기

왜 파일을 다루나?

프로그램과 데이터 영속성:

프로그램을 종료하면 변수에 저장된 데이터는 사라집니다. 하지만 파일에 저장하면 영구히 보존됩니다!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# ❌ 메모리에만 저장 (프로그램 종료 시 사라짐)
score = 100
name = "홍길동"
# 프로그램 종료 → 데이터 손실!

# ✅ 파일에 저장 (영구 보존)
# 게임 점수를 파일에 저장
file = open("game_save.txt", "w")
file.write("홍길동\n")
file.write("100\n")
file.close()

# 나중에 다시 불러오기
file = open("game_save.txt", "r")
saved_name = file.readline().strip()
saved_score = file.readline().strip()
file.close()

print(f"{saved_name}님의 점수: {saved_score}")  # 홍길동님의 점수: 100

💡 핵심: 파일은 프로그램이 종료되어도 데이터가 남아있습니다!

파일 입출력의 용도:

  1. 데이터 저장: 설정, 사용자 정보, 게임 세이브
  2. 로그 기록: 애플리케이션 실행 기록
  3. 데이터 교환: CSV, JSON 등 표준 포맷
  4. 리소스 관리: 이미지, 동영상 등 미디어 파일

파일 처리 플로우

graph LR
    A[프로그램] -->|1. open| B[파일 열기]
    B -->|2. read/write| C[파일 작업]
    C -->|3. close| D[파일 닫기]
    D --> A

    style B fill:#e1f5ff
    style C fill:#fff4e1
    style D fill:#ffe1e1

open() 함수 기초

1
2
# 기본 문법
file = open(filename, mode, encoding='utf-8')

파일 모드:

모드 설명 파일 없을 때 파일 있을 때
'r' 읽기 (기본) 오류 발생 읽기
'w' 쓰기 새로 생성 덮어쓰기 (주의!)
'a' 추가 새로 생성 끝에 추가
'x' 배타적 생성 새로 생성 오류 발생
'r+' 읽기+쓰기 오류 발생 읽기/쓰기
'w+' 읽기+쓰기 새로 생성 덮어쓰기
'a+' 읽기+추가 새로 생성 끝에 추가

바이너리 모드: 'rb', 'wb', 'ab'

수동 파일 닫기

1
2
3
4
5
6
7
8
9
10
# ❌ 위험한 방법 (권장하지 않음)
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()  # close()를 잊으면 문제 발생!

# 예외 발생 시 close()가 실행되지 않음
file = open("example.txt", "w")
file.write("Hello")
# ... 여기서 오류 발생하면 파일이 닫히지 않음!
file.close()

문제점:

  • close()를 잊을 수 있음
  • 예외 발생 시 파일이 닫히지 않음
  • 리소스 누수 (메모리, 파일 핸들)

🎯 학습 목표 2: 텍스트 파일 읽기

파일 전체 읽기 - read()

1
2
3
4
5
# 전체 내용을 하나의 문자열로
with open("story.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)
    print(f"{len(content)}")

주의사항:

  • 대용량 파일은 메모리 부족 가능
  • 작은 파일(< 1MB)에 적합

한 줄씩 읽기 - readline()

1
2
3
4
5
6
7
8
9
# 한 줄씩 읽기
with open("data.txt", "r") as f:
    line1 = f.readline()  # 첫 번째 줄
    line2 = f.readline()  # 두 번째 줄
    line3 = f.readline()  # 세 번째 줄

    print(line1)
    print(line2)
    print(line3)

줄바꿈 문자 제거:

1
2
3
4
with open("data.txt", "r") as f:
    line = f.readline()
    print(repr(line))        # 'Hello\n'
    print(repr(line.strip())) # 'Hello' (줄바꿈 제거)

모든 줄을 리스트로 - readlines()

1
2
3
4
5
6
7
# 모든 줄을 리스트로
with open("todo.txt", "r") as f:
    lines = f.readlines()

print(f"{len(lines)}개 항목:")
for i, line in enumerate(lines, 1):
    print(f"{i}. {line.strip()}")

가장 효율적인 방법 - 파일 객체 이터레이션

1
2
3
4
5
# ✅ 권장: 파일 객체를 직접 순회
with open("large_file.txt", "r") as f:
    for line in f:
        # 한 줄씩 처리 (메모리 효율적!)
        print(line.strip())

장점:

  • 메모리 효율적 (한 줄씩 읽음)
  • 대용량 파일에 적합
  • 코드 간결

실전 예제: 로그 파일 분석

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def analyze_log(filename):
    """로그 파일에서 ERROR 라인 찾기"""
    error_count = 0
    errors = []

    with open(filename, "r") as f:
        for line_num, line in enumerate(f, 1):
            if "ERROR" in line:
                error_count += 1
                errors.append((line_num, line.strip()))

    print(f"{error_count}개의 ERROR 발견:")
    for line_num, error in errors:
        print(f"  라인 {line_num}: {error}")

# 사용
# analyze_log("application.log")

파일 포인터와 탐색

tell() - 현재 위치

1
2
3
4
5
6
7
8
with open("data.txt", "r") as f:
    print(f"초기 위치: {f.tell()}")  # 0

    f.read(5)
    print(f"5자 읽은 후: {f.tell()}")  # 5

    f.readline()
    print(f"한 줄 읽은 후: {f.tell()}")

seek() - 위치 이동

1
2
3
4
5
6
7
8
9
10
11
12
with open("data.txt", "r") as f:
    # 처음부터
    f.seek(0)
    content1 = f.read()

    # 다시 처음으로
    f.seek(0)
    content2 = f.read()

    # 10번째 바이트로
    f.seek(10)
    rest = f.read()

seek() 모드:

  • seek(offset, 0): 파일 시작부터 (기본)
  • seek(offset, 1): 현재 위치부터
  • seek(offset, 2): 파일 끝부터

실전 예제: 파일 끝에서 N줄 읽기

1
2
3
4
5
6
7
8
9
10
def tail(filename, n=10):
    """파일의 마지막 N줄 읽기 (Unix tail 명령)"""
    with open(filename, "r") as f:
        lines = f.readlines()
        return lines[-n:]

# 사용
last_lines = tail("log.txt", n=5)
for line in last_lines:
    print(line.strip())

🎯 학습 목표 3: 텍스트 파일 쓰기와 추가

파일에 쓰기 - write()

1
2
3
4
5
6
7
8
9
10
# 새 파일 생성 또는 덮어쓰기 (주의!)
with open("output.txt", "w") as f:
    f.write("첫 번째 줄\n")
    f.write("두 번째 줄\n")
    f.write("세 번째 줄\n")

# output.txt:
# 첫 번째 줄
# 두 번째 줄
# 세 번째 줄

주의: write()는 자동 줄바꿈 안 함! 직접 \n 추가

여러 줄 쓰기 - writelines()

1
2
3
4
5
6
7
8
9
10
11
12
13
lines = [
    "Apple\n",
    "Banana\n",
    "Cherry\n"
]

with open("fruits.txt", "w") as f:
    f.writelines(lines)

# 또는 리스트 컴프리헨션
fruits = ["Apple", "Banana", "Cherry"]
with open("fruits.txt", "w") as f:
    f.writelines(f"{fruit}\n" for fruit in fruits)

파일에 추가 - 'a' 모드

1
2
3
4
5
6
# 기존 파일 끝에 추가
with open("log.txt", "a") as f:
    f.write("새로운 로그 항목\n")

# 파일이 없으면 새로 생성
# 파일이 있으면 끝에 추가 (덮어쓰지 않음)

실전 예제: 간단한 일기장

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from datetime import datetime

def write_diary():
    """일기 작성"""
    entry = input("오늘의 일기: ")
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    with open("diary.txt", "a", encoding="utf-8") as f:
        f.write(f"\n[{timestamp}]\n")
        f.write(f"{entry}\n")
        f.write("-" * 50 + "\n")

    print("✅ 일기가 저장되었습니다!")

def read_diary():
    """일기 읽기"""
    try:
        with open("diary.txt", "r", encoding="utf-8") as f:
            content = f.read()
            print("\n📔 나의 일기장")
            print("=" * 50)
            print(content)
    except FileNotFoundError:
        print("아직 작성된 일기가 없습니다.")

# 사용
# write_diary()
# read_diary()

🎯 학습 목표 4: with 문으로 안전한 파일 처리

with 문이란?

Context Manager: 리소스를 자동으로 관리하는 Python의 강력한 기능

1
2
3
4
5
6
7
# ✅ 권장하는 방법
with open("example.txt", "w") as f:
    f.write("Hello, World!")
    # with 블록을 벗어나면 자동으로 close() 호출

# 파일이 이미 닫혀 있음
# f.write("More")  # ValueError: I/O operation on closed file

장점:

  1. 자동 리소스 관리: 블록 종료 시 자동으로 close()
  2. 예외 안전: 예외 발생해도 파일 닫힘
  3. 코드 간결: 명시적 close() 불필요

예외 상황에서도 안전

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# ❌ 수동 close(): 예외 발생 시 파일이 닫히지 않음
try:
    f = open("data.txt", "w")
    # 오류 발생!
    result = 1 / 0
    f.close()  # 실행되지 않음!
except:
    pass

# ✅ with 문: 예외 발생해도 파일이 닫힘
try:
    with open("data.txt", "w") as f:
        # 오류 발생!
        result = 1 / 0
        # 파일은 자동으로 닫힘!
except:
    pass

여러 파일 동시 처리

1
2
3
4
5
6
7
8
9
# 여러 파일 동시 처리
with open("input.txt", "r") as input_file, \
     open("output.txt", "w") as output_file:

    for line in input_file:
        # 각 줄을 대문자로 변환하여 출력 파일에 쓰기
        output_file.write(line.upper())

# 두 파일 모두 자동으로 닫힘

실전 예제: 안전한 파일 변환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def convert_file(input_file, output_file, converter):
    """안전한 파일 변환 처리"""
    try:
        with open(input_file, "r", encoding="utf-8") as fin, \
             open(output_file, "w", encoding="utf-8") as fout:

            for line in fin:
                converted = converter(line)
                fout.write(converted)

        print(f"✅ 변환 완료: {input_file}{output_file}")
        return True

    except FileNotFoundError:
        print(f"❌ 파일 없음: {input_file}")
        return False

    except Exception as e:
        print(f"❌ 오류 발생: {e}")
        return False

# 사용 예제
# convert_file("data.txt", "uppercase.txt", str.upper)

🎯 학습 목표 5: 파일 인코딩과 바이너리 모드

인코딩이란?

인코딩(Encoding): 문자를 바이트로 변환하는 방식

1
2
3
4
5
6
7
# UTF-8 인코딩 (권장)
with open("한글.txt", "w", encoding="utf-8") as f:
    f.write("안녕하세요, Python!")

# CP949 인코딩 (Windows 한글)
with open("한글_cp949.txt", "w", encoding="cp949") as f:
    f.write("안녕하세요, Python!")

인코딩 오류 처리

1
2
3
4
5
6
7
8
9
10
# ❌ 인코딩 불일치 오류
try:
    with open("utf8_file.txt", "r", encoding="cp949") as f:
        content = f.read()
except UnicodeDecodeError as e:
    print(f"인코딩 오류: {e}")

# ✅ 올바른 인코딩
with open("utf8_file.txt", "r", encoding="utf-8") as f:
    content = f.read()

인코딩 자동 감지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# chardet 라이브러리 사용 (별도 설치 필요)
# pip install chardet

import chardet

def detect_encoding(filename):
    """파일 인코딩 자동 감지"""
    with open(filename, "rb") as f:
        raw_data = f.read()

    result = chardet.detect(raw_data)
    return result['encoding']

# 사용
# encoding = detect_encoding("unknown_encoding.txt")
# with open("unknown_encoding.txt", "r", encoding=encoding) as f:
#     content = f.read()

일반적인 인코딩

인코딩 설명 용도
utf-8 유니코드 (권장) 전세계 모든 문자
cp949 Windows 한글 레거시 한글 파일
euc-kr Unix 한글 레거시 한글 파일
ascii 영문/숫자 영문만
latin-1 서유럽 문자 특수 문자 포함

권장: 항상 encoding="utf-8" 명시!


바이너리 모드

1
2
3
4
5
6
7
8
9
# 바이너리 읽기
with open("image.png", "rb") as f:
    data = f.read()
    print(f"파일 크기: {len(data)} bytes")
    print(f"처음 10바이트: {data[:10]}")

# 바이너리 쓰기
with open("copy.png", "wb") as f:
    f.write(data)

실전 예제: 파일 복사

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def copy_file(source, destination):
    """파일 복사 (바이너리 안전)"""
    with open(source, "rb") as src, \
         open(destination, "wb") as dst:

        # 청크 단위로 복사 (대용량 파일 안전)
        chunk_size = 1024 * 1024  # 1MB
        while True:
            chunk = src.read(chunk_size)
            if not chunk:
                break
            dst.write(chunk)

    print(f"✅ 복사 완료: {source}{destination}")

# 사용
# copy_file("photo.jpg", "photo_backup.jpg")

바이너리 데이터 다루기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 바이트 객체
data = b"Hello"  # bytes
print(type(data))  # <class 'bytes'>
print(data[0])     # 72 (ASCII 'H')

# 바이트 배열 (수정 가능)
data = bytearray(b"Hello")
data[0] = ord('h')  # 'H' → 'h'
print(data)  # bytearray(b'hello')

# 문자열 <-> 바이트 변환
text = "안녕하세요"
bytes_data = text.encode("utf-8")
text_again = bytes_data.decode("utf-8")

print(bytes_data)   # b'\xec\x95\x88\xeb\x85\x95\xed\x95\x98\xec\x84\xb8\xec\x9a\x94'
print(text_again)   # 안녕하세요

🎯 학습 목표 6: 파일 관리와 정보 확인

os.path 모듈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os

filename = "example.txt"

# 파일 존재 확인
if os.path.exists(filename):
    print(f"{filename} 존재함")
else:
    print(f"{filename} 없음")

# 파일인지 디렉토리인지
if os.path.isfile(filename):
    print("파일입니다")
elif os.path.isdir(filename):
    print("디렉토리입니다")

# 파일 크기
size = os.path.getsize(filename)
print(f"파일 크기: {size} bytes ({size / 1024:.2f} KB)")

# 절대 경로
abs_path = os.path.abspath(filename)
print(f"절대 경로: {abs_path}")

pathlib 모듈 (Python 3.4+)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from pathlib import Path

file = Path("example.txt")

# 존재 확인
if file.exists():
    print("파일 존재")

# 파일 읽기 (간편)
content = file.read_text(encoding="utf-8")

# 파일 쓰기 (간편)
file.write_text("Hello, World!", encoding="utf-8")

# 파일 정보
print(f"이름: {file.name}")
print(f"확장자: {file.suffix}")
print(f"크기: {file.stat().st_size} bytes")
print(f"수정 시간: {file.stat().st_mtime}")

실전 예제: 안전한 파일 쓰기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os

def safe_write(filename, content):
    """기존 파일을 백업하고 안전하게 쓰기"""
    # 기존 파일이 있으면 백업
    if os.path.exists(filename):
        backup_name = f"{filename}.backup"

        # 백업 파일이 이미 있으면 덮어쓰기
        if os.path.exists(backup_name):
            os.remove(backup_name)

        os.rename(filename, backup_name)
        print(f"💾 백업 생성: {backup_name}")

    # 새 파일 쓰기
    with open(filename, "w", encoding="utf-8") as f:
        f.write(content)

    print(f"✅ 파일 저장: {filename}")

# 사용
# safe_write("important.txt", "중요한 내용")

💡 실전 종합 예제

예제 1: 단어 빈도 분석기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from collections import Counter
import re

def word_frequency(filename):
    """텍스트 파일의 단어 빈도 분석"""
    with open(filename, "r", encoding="utf-8") as f:
        text = f.read().lower()

    # 단어 추출 (알파벳과 한글만)
    words = re.findall(r'[a-z가-힣]+', text)

    # 빈도 계산
    freq = Counter(words)

    # 상위 10개
    print(f"\n📊 {filename} 단어 빈도 (상위 10개)")
    print("=" * 50)
    for word, count in freq.most_common(10):
        print(f"{word:20s} : {count:3d}")

# 사용
# word_frequency("article.txt")

예제 2: CSV 간단 처리 (직접 구현)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def read_csv(filename):
    """CSV 파일 읽기 (간단 버전)"""
    rows = []

    with open(filename, "r", encoding="utf-8") as f:
        for line in f:
            # 쉼표로 분리
            row = line.strip().split(",")
            rows.append(row)

    return rows

def write_csv(filename, rows):
    """CSV 파일 쓰기"""
    with open(filename, "w", encoding="utf-8") as f:
        for row in rows:
            # 쉼표로 결합
            line = ",".join(str(cell) for cell in row)
            f.write(line + "\n")

# 사용 예제
data = [
    ["이름", "나이", "직업"],
    ["Alice", "25", "개발자"],
    ["Bob", "30", "디자이너"],
    ["Charlie", "28", "기획자"]
]

write_csv("people.csv", data)

loaded_data = read_csv("people.csv")
for row in loaded_data:
    print(row)

예제 3: 설정 파일 관리

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def load_config(filename="config.txt"):
    """설정 파일 로드 (key=value 형식)"""
    config = {}

    try:
        with open(filename, "r") as f:
            for line in f:
                line = line.strip()

                # 빈 줄이나 주석 무시
                if not line or line.startswith("#"):
                    continue

                # key=value 파싱
                if "=" in line:
                    key, value = line.split("=", 1)
                    config[key.strip()] = value.strip()

    except FileNotFoundError:
        print(f"⚠️ 설정 파일 없음: {filename}")
        return {}

    return config

def save_config(config, filename="config.txt"):
    """설정 파일 저장"""
    with open(filename, "w") as f:
        f.write("# 설정 파일\n\n")
        for key, value in config.items():
            f.write(f"{key} = {value}\n")

# 사용
config = {
    "app_name": "MyApp",
    "version": "1.0",
    "debug": "true"
}

save_config(config)
loaded = load_config()
print(loaded)

💡 실전 팁 & 주의사항

Tip 1: 항상 with 문을 사용하세요

1
2
3
4
5
6
7
8
9
# ❌ 나쁜 예: 수동으로 닫기
f = open("file.txt", "r")
content = f.read()
f.close()  # 에러 발생 시 실행되지 않을 수 있음!

# ✅ 좋은 예: with 문 사용
with open("file.txt", "r") as f:
    content = f.read()
# 자동으로 닫힘!

이유: with 문은 예외가 발생해도 파일을 자동으로 닫아줍니다.

Tip 2: 인코딩을 명시하세요

1
2
3
4
5
6
7
# ❌ 나쁜 예: 인코딩 생략 (시스템 기본값 사용)
with open("한글파일.txt", "r") as f:
    content = f.read()  # Windows에서 에러 발생 가능!

# ✅ 좋은 예: UTF-8 명시
with open("한글파일.txt", "r", encoding="utf-8") as f:
    content = f.read()

이유: 시스템마다 기본 인코딩이 다르므로 명시해야 호환성이 좋습니다.

Tip 3: 대용량 파일은 한 줄씩 읽으세요

1
2
3
4
5
6
7
8
9
10
# ❌ 나쁜 예: 전체를 메모리에 로드
with open("huge.txt", "r") as f:
    content = f.read()  # 메모리 부족 위험!
    for line in content.splitlines():
        process(line)

# ✅ 좋은 예: 한 줄씩 순회
with open("huge.txt", "r") as f:
    for line in f:  # 메모리 효율적!
        process(line.strip())

이유: 대용량 파일을 한 번에 읽으면 메모리 부족이 발생할 수 있습니다.


🧪 연습 문제

문제 1: 줄 번호 추가기

파일의 각 줄 앞에 줄 번호를 추가하는 프로그램을 작성하세요.

입력 (input.txt):

1
2
3
Hello
World
Python

출력 (output.txt):

1
2
3
1: Hello
2: World
3: Python
해답 보기
1
2
3
4
5
6
7
8
9
10
11
def add_line_numbers(input_file, output_file):
    """줄 번호 추가"""
    with open(input_file, "r", encoding="utf-8") as fin, \
         open(output_file, "w", encoding="utf-8") as fout:

        for line_num, line in enumerate(fin, 1):
            fout.write(f"{line_num}: {line}")

# 테스트
add_line_numbers("input.txt", "output.txt")
print("✅ 완료!")

문제 2: 파일 합치기

여러 개의 텍스트 파일을 하나로 합치는 함수를 작성하세요.

해답 보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def merge_files(input_files, output_file):
    """여러 파일을 하나로 합치기"""
    with open(output_file, "w", encoding="utf-8") as fout:
        for i, input_file in enumerate(input_files, 1):
            # 파일 구분선
            fout.write(f"\n{'='*50}\n")
            fout.write(f"파일 {i}: {input_file}\n")
            fout.write(f"{'='*50}\n\n")

            # 파일 내용
            try:
                with open(input_file, "r", encoding="utf-8") as fin:
                    fout.write(fin.read())
                    fout.write("\n")
            except FileNotFoundError:
                fout.write(f"⚠️ 파일을 찾을 수 없습니다: {input_file}\n")

# 테스트
files = ["file1.txt", "file2.txt", "file3.txt"]
merge_files(files, "merged.txt")
print("✅ 파일 합치기 완료!")

문제 3: 파일 통계

텍스트 파일의 통계(줄 수, 단어 수, 문자 수)를 출력하는 함수를 작성하세요.

해답 보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def file_statistics(filename):
    """파일 통계"""
    try:
        with open(filename, "r", encoding="utf-8") as f:
            content = f.read()
            lines = content.splitlines()
            words = content.split()
            chars = len(content)

            print(f"\n📊 {filename} 통계")
            print("=" * 50)
            print(f"줄 수:   {len(lines):,}")
            print(f"단어 수: {len(words):,}")
            print(f"문자 수: {chars:,}")
            print(f"파일 크기: {os.path.getsize(filename):,} bytes")

    except FileNotFoundError:
        print(f"❌ 파일을 찾을 수 없습니다: {filename}")

# 테스트
import os
file_statistics("article.txt")

📝 오늘 배운 내용 정리

개념 설명 예시
파일 열기 open(filename, mode, encoding) open("file.txt", "r", encoding="utf-8")
파일 모드 'r' (읽기), 'w' (쓰기), 'a' (추가) open("file.txt", "w")
with 문 자동 리소스 관리 with open("file.txt") as f:
읽기 메서드 read(), readline(), readlines() f.read()
쓰기 메서드 write(), writelines() f.write("Hello")
인코딩 텍스트 파일의 문자 집합 encoding="utf-8"
바이너리 모드 이미지, 동영상 등 처리 open("image.png", "rb")

핵심 코드 패턴

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 파일 읽기
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()

# 파일 쓰기
with open("file.txt", "w", encoding="utf-8") as f:
    f.write("내용")

# 파일 추가
with open("file.txt", "a", encoding="utf-8") as f:
    f.write("추가 내용\n")

# 줄 단위 처리 (권장)
with open("file.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

🔗 관련 자료

📚 이전 학습

Day 40: 미니 프로젝트: 도서 관리 시스템 ⭐⭐⭐⭐

어제는 Phase 4의 모든 객체지향 개념을 활용해 도서 관리 시스템을 완성했습니다!

📚 다음 학습

Day 42: 텍스트 파일 고급 처리 ⭐⭐⭐

내일은 정규표현식을 활용한 파일 처리, 대용량 파일 효율적 처리, 파일 검색 및 필터링을 배웁니다!


“늦었다고 생각할 때가 가장 빠른 시기입니다!” 🚀

Day 41/100 Phase 5: 파일 처리와 예외 처리 #100DaysOfPython
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.