⏰ 2024.12.23 (D+53)
- 파이썬에서 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)
- 텍스트 파일을 쓰기 모드(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)
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]) # 각 줄의 공백 제거
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())
- 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))
- StringIO는 메모리 내에서 문자열을 파일처럼 다룰 수 있게 해주는 클래스
- 텍스트 데이터를 메모리에서 읽고 쓸 수 있다
from io import StringIO s_io = StringIO() s_io.write('안녕하세요\nHELLO') s_io.seek(0) print(s_io.read()) s_io.close()
- 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())