파이썬 파일 입출력 및 예외 처리 활용법

YeHee·2024년 12월 26일

⏰ 2024.12.23 (D+53)

1. 나만의 예외 만들기

  • 파이썬에서 Exception 클래스를 상속받아 나만의 예외를 만들 수 있다
  • __init__() 메소드에서 Exception 클래스의 __init__() 메소드를 호출하며 예외 메시지를 전달
# 방법 1
class NotEvenException(Exception):
    def __init__(self):
        super().__init__('짝수가 아니예요')

try:
    value = int(input('숫자 입력?'))
    if value % 2 != 0:
        raise NotEvenException()
    print(f'{value}는 짝수예요')
except NotEvenException as e:
    print(e)

# 방법 2
class NotEvenException(Exception):
    def __init__(self, errorMessage):
        super().__init__(errorMessage)

try:
    value = int(input('숫자 입력?'))
    if value % 2 != 0:
        if value > 100:
            raise NotEvenException('100보다 큰 홀수 입니다')
        else:
            raise NotEvenException('100보다 작은 홀수 입니다')
    print(f'{value}는 짝수예요')
except NotEvenException as e:
    print(e)

# 방법 3
class NotEvenException(Exception):
    pass

try:
    value = int(input('숫자 입력?'))
    if value % 2 != 0:
        if value > 100:
            raise NotEvenException('100보다 큰 홀수 입니다')
        else:
            raise NotEvenException('100보다 작은 홀수 입니다')
    print(f'{value}는 짝수예요')
except NotEvenException as e:
    print(e)

2. 파일 처리 (쓰기 모드)

  • 텍스트 파일을 쓰기 모드(w)로 열면 파일이 없으면 생성
  • 기존 파일이 있으면 덮어쓴다
try:
    with open('line.txt', 'wt', encoding='utf-8') as f:
        f.write('파일 쓰기 시작')
        for i in range(1, 11):
            textLine = f'\n{i}번째 라인 입니다'
            f.write(textLine)
        f.write('\n파일 쓰기 종료')
except Exception as e:
    print(e)

3. 파일 처리 (읽기 모드)

  • read(), readline(), readlines() 등을 사용하여 파일에서 데이터를 읽을 수 있다
  • read()는 전체 파일 내용을, readline()은 한 줄씩, readlines()는 모든 라인을 읽어서 리스트로 반환
with open('list.txt', 'r', encoding='utf8') as f:
    print(f.read())  # 전체 내용 읽기

with open('list.txt', 'r', encoding='utf8') as f:
    lines = f.readlines()
    print([line.strip() for line in lines])  # 각 줄의 공백 제거

4. 파일 모드 (w+, r+, a+)

w+: 읽기 및 쓰기 가능, 파일이 없으면 새로 생성, 기존 내용은 삭제
r+: 읽기 및 쓰기 가능, 파일이 없으면 에러 발생
a+: 읽기 및 쓰기 가능, 파일이 없으면 생성, 내용은 기존 데이터 뒤에 추가

# w+ 모드 예시
with open('w_plus.txt', 'w+', encoding='utf8') as f:
    f.write('1234567890')
    f.seek(0)
    print(f.read())

# r+ 모드 예시
with open('r_plus.txt', 'r+', encoding='utf8') as f:
    print(f.read())
    f.write('\n1234567890')
    f.seek(0)
    print(f.read())

# a+ 모드 예시
with open('a_plus.txt', 'a+', encoding='utf8') as f:
    f.write('\n1234567890')
    f.seek(0)
    print(f.read())

5. 바이너리 모드로 파일 읽고 쓰기 (pickle)

  • pickle을 사용하여 파이썬 객체를 바이너리 파일로 저장하거나 로드할 수 있다
import pickle

name = '가길동'
age = 20
with open('object.txt', 'wb') as f:
    pickle.dump(name, f)
    pickle.dump(age, f)

with open('object.txt', 'rb') as f:
    print(pickle.load(f))
    print(pickle.load(f))

6. StringIO 사용

  • StringIO는 메모리 내에서 문자열을 파일처럼 다룰 수 있게 해주는 클래스
  • 텍스트 데이터를 메모리에서 읽고 쓸 수 있다
from io import StringIO

s_io = StringIO()
s_io.write('안녕하세요\nHELLO')
s_io.seek(0)
print(s_io.read())
s_io.close()

7. BytesIO 사용

  • BytesIO는 바이트 데이터를 메모리에서 파일처럼 다룰 수 있게 해주는 클래스
  • 이진 데이터를 메모리에서 읽고 쓸 수 있다
from io import BytesIO
import base64

b_io = BytesIO()
b_io.write('안녕하세요'.encode())
b_io.seek(0)
bytes_ = b_io.read()
print(bytes_)
print(bytes_.decode())

with open('lion.jpg', 'rb') as f:
    with BytesIO(f.read()) as b_io:
        bytes_ = b_io.read()
        base64_ = base64.b64encode(bytes_)
        print(base64_.decode())

0개의 댓글