Part 3. Python Basics for AI
chapter 3) Exception / File / Log Handling
네이버 AI 부스트캠프의 Pre-course 수업을 듣던 중 공부한 내용을 정리하고, 추가적으로 따로 공부한 부분이 생기면 함께 필기했습니다.
대부분의 캡쳐, 정보는 부스트캠프 강의에서 얻었으며 오직 개인 공부의 목적으로 포스팅합니다.
강의 링크는 여기에
<기본 형식>
try:
예외 발생 가능 코드
except <Exception Type>:
예외 발생시 대응하는 코드
<밑에 추가적으로 적을 수 있는 코드들>
else:
예외가 발생하지 않을 때 동작하는 코드
finally:
예외 발생 여부와 상관없이 실행됨
Built-in Exception Type: 기본적으로 제공하는 예외
1) IndexError : List의 Index 범위를 넘어갈 때
2) NameError : 존재하지 않은 변수를 호출할 때
3) ZeroDivisionError : 0으로 숫자를 나눌 때
4) ValueError : 변환할 수 없는 문자/숫자를 변환할 때
5) FileNotFoundError : 존재하지 않는 파일을 호출할 때
<기본 형식>
raise <Exception Type>(예외정보)
<예제>
while True:
value = input("변환할 정수값 입력")
for digit in value:
if digit not in "0123456789":
raise ValueError("숫자값을 입력하지 않으셨습니다")
print("정수값으로 변환된 숫자 -", int(value))
<기본 형식>
assert 예외조건
<예제>
def get_binary_nmubmer(decimal_number):
assert isinstance(decimal_number, int)
return bin(decimal_number)
print(get_binary_nmubmer(10)
f = open("<파일이름>", "접근모드")
f.close()
f = open("i_have_a_dream.txt", "r")
contents = f.read()
print(contents)
f.close()
with open("i_have_a_dream.txt", "r") as my_file:
contents = f.read()
print(type(contents), contents)
with open("i_have_a_dream.txt", "r") as my_file:
i = 0
while True:
line = my_file.readline() #한 줄씩 읽기
if not line:
break
print(str(i) + " === " + line.replace("\n",""))
i = i + 1
import os
os.mkdir("log") # make directory
1) os.path.isdir("폴더이름")
<예제>
if not os.path.isdir("log"):
#"log"라는 경로가 없으면:
os.mkdir("log")
#"log"파일을 만들어라
2) os.path.exists("파일이름")
True/False 반환으로 알려줌
<예제>
(1) 디렉토리 존재 여부, 파일 존재 여부 확인 후
if not os.path.exists("log"/count_log.txt"):
f = open("log/count_log.txt", 'w', encoding="utf8")
f.write("기록이 시작됩니다\n")
f.close()
(2) 그리고 생성 시작
with open("log/count_log.txt", 'a', encoding = "utf8") as f:
import random, datetime
for i in range(1,11):
stamp = str(datetime.datetime.now())
value = random.random() * 1000000
log_line = stamp + "\t" + str(value) + "값이 생성되었습니다" + "\n"
f.write(log_line)
3) os.path.isfile("file.ipynb") 등 다양한 방법이 있음.
import pathlib
cwb = pathlib.Path.cwd()
cwb.parent
#'폴더1\폴더2\파일1'일때 파일1은빼고 '폴더1\폴더2'까지의 경로를 보여줌.
cwb.parent.parents
#'폴더1' 뒤의 폴더2의 부모니까 폴더1까지만.
<예제>
import pickle
f = open("list.pickle", "wb")
# 'wb' = write binary, 파일로 만듦
test = [1, 2, 3, 4, 5]
pickle dump(test,f)
f.close()
del test
# 메모리 안에 test파일 지우기. test 쳐서 불러도 안나옴
f = open("list.pickle", "rb")
# 'rb' = read binary
test_pickle = pickle.load(f)
print(test_pickle)
f.close()
Python의 기본 Log 관리 모듈
1. 기본적인 Logging 방법
import logging
steam_handler = logging.FileHandler(
"my.log", mode="a", encoding="utf8")
logger.addHandler(steam_handler)
실제 프로그램을 실행할 땐 여러 설정이 필요한데(데이터 파일 위치, 저장 위치 등) 이러한 정보를 설정해 줄 방법에는 크게 2가지가 있다.
pickle, config parser, arg parser 추가 공부할 것.