try:
예외 발생 가능 코드
except <Exception Type>:
예외 발생시 대응 코드
for i in range(10):
try:
print(10/i) # i = 0 일때 나눌 수 없어서 exception이 발생
except ZeroDivisionError: # 이 때 해당 exception을 캐치하여 어떤 해당 조건과 맞는 exception일 경우 대응 코드로 진행
print("Not divided by 0")
except Exception as e:
print(e) #다른 exception이 발생할 경우 어떤 error인지 파악하기 위해, 일반적으로 마지막 except에 해당 코드를 추가해줌
# 단, 이렇게 모든 exception을 잡게 될 경우 어디서 error가 발생한지 명확하지 않으므로 좋은 코드는 아님
# 초기 코드 작성 경우에만 사용할 것
try:
예외 발생 가능 코드
except <Exception Type>:
예외 발생 시 동작하는 코드
else:
예외가 발생하지 않을 때 동작하는 코드
try:
예외 발생 가능 코드
except <Exception Type>:
예외 발생 시 동작하는 코드
finally:
예외 발생 여부와 상관없이 동작하는 코드
raise <Exception Type>(예외 정보)
while True:
value = input("변환할 정수 값을 입력: )
for digit in value:
if digit not in "0123456789":
raise ValueError("숫자값을 입력하지 않으셨습니다")
print("정수값으로 변환된 숫자 -", int(value))
asswer 예외조건
def get_binary_number(decimal_number : int):
assert isinstance(decimal_number, int)
# 타입 힌트를 넣어줬더라도 사용자가 잘못 입력한 경우가 있음
# 이럴 isinstance()로 True or False가 출력되는데
# False일 경우 Error를 출력하고 진행을 멈춤
# 에러가 발생할 경우 다음 과정을 진행할 필요가 없으므로 리소스 방지를 위해 멈춰줌
return bin(decimal_number)
print(get_binary_number(10)
파이썬은 파일 처리를 위해 "Open" 키워드 사용
f = open("<파일이름>", "접근 모드")
f.close()
접근 모드
file read
f = open("dream.txt","r") #대상 파일이 같은 폴더에 있을 경우
contents = f.read()
f.close()
with open("dream.txt","r") as my_file:
contents = my_file.read()
with open("dream.txt","r") as my_file:
contents = my_file.readlines() #파일 전체를 list로 반환
with open("dream.txt","r") as my_file:
i = 0
while True:
line = my_file.readline() #한 줄씩 읽어옴
if not line:
break
print(str(i) + "===" + line.replace("\n",""))
- read, readlines, readline
- read : 통째로 읽음
- readlines : 띄어쓰기 기준으로 한 줄씩 읽어서 list에 저장
- readline : 한 줄씩 읽음
- readlines는 실행 시 모든 라인을 데이터에 올리는데 대용량 데이터 처리 시 매우 느림
- 그럴 때 한줄씩 읽어서 메모리에 올리는 readline이 좋음
File Write
f = open("count_log.txt","w",encoding = "utf8")
for i in range(1,11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
f.close()
with open("dream.txt","w",encoding = 'utf8') as my_file:
for i in range(1,11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
import os
if not os.path.isdir("log"): #디렉토리 있는지 확인
os.mkdir("log") #디렉토리 생성
# os.path.isdir( ) == os.path.exists( )
try:
os.mkdir("abc")
except FileExistError as e:
print("Already created")
os.path.isfile() #파일 존재 여부 확인
import shutil
source = "file.ipynb" #현재 위치에 있는 파일 명
dest = os.path.join("abc", "file1.ipynb")
# 경로 생성 => abc\\file.ipynb
# join구문을 사용하는 이유 : os가 다를 경우 발생할 문제 방지
# directory구분 => windows : \, mac : /
shutil.copy(source, dest) #source 파일을 해당 위치의 지정한 파일명으로 복사
import pathlib
cwd = pathlib.Path.cwd() #현재 위치의 절대 경로를 저장
cwd.Parent # 상위 디렉토리 출력
list(cwd.Parents) # 현재 위치부터 최상단 위치까지 디렉토리 경로 출력
cwd.glob("*") # 현재 폴더의 모든 파일을 절대경로와 함께 출력
import os
if not os.path.isdir("log"):
os.mkdir("log")
target_file_path = os.path.join("log", "count_log.txt")
if not os.path.exists(target_file_path):
f = open("log/count_log.txt", "w", encoding = "utf8")
f = write("기록이 시작됩니다 \n")
f.close()
with open(target_file_path, "w", 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)
객체는 기본적으로 메모리에 저장되고, 파이썬 인터프리터가 종료 시 삭제됨
이 때, 해당 객체를 추후에도 사용하려고 할 때 객체를 외부에 저장해야 함
파이썬의 객체를 영속화(persistence)하는 built-in 객체
데이터,object, 모델 등을 저장하고 불러와서 사용하는 기능을 제공
binary 파일로 txt로 열 수 없음
import pickle
#write
f = open("tmp.pickle",wb") #wb : write binary
test = [1,2,3]
pickle.dump(test,f)
f.close()
#read
f = open("tmp.pickle", "rb") #rb : read binary
test = pickle.load(f)
f.close()