사소하지만, 모르면 프로그래밍시 힘들 수 있다.
1) 예상 가능한 예외
2) 예상이 불가능한 예외
try ~ except
문법try:
# 예외 발생 코드
except<Exception Type>:
# 예외 발생시 대응하는 코드
Built-in Exception : 기본적으로 제공하는 예외
1) IndexError
: List의 Index 범위를 넘어갈 때
2) NameError
: 존재하지 않은 변수를 호출 할 때
3) ZeroDivisionError
: 0으로 숫자를 나눌 때
4) ValueError
: 변환할 수 없는 문자/숫자를 변환할 때
5) FileNotFoundError
: 존재하지 않는 파일을 호출할 때
try ~ except ~ else
try:
# 예외 발생 가능 코드
except <Exception Type> :
# 예외 발생시 동작하는 코드
else:
# 예외가 발생하지 않을 떄 동작하는 코드
try ~ except ~ finally
try:
# 예외 발생 가능 코드
except <Exception Type>:
# 예외 발생시 동작하는 코드
finally:
# 예외 발생 여부와 상관없이 실행됨
raise
: 필요에 따라 강제로 Exception을 발생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))
open
키워드를 사용함 f = open("<파일이름>", "접근 모드") # 접근모드 'r' : 읽기모드, 'w' : 쓰기모드, 'a' : 추가모드
f.close()
read()
: txt파일 안에 있는 내용을 문자열로 반환f = open("i_have_a_draem.txt", "r")
contents = f.read()
print(contents)
f.close()
with
구문과 함께 사용하기with open("i_have_a_dream.txt", "r") as my_file:
contents = my_file.read()
print (type(contents), contents)
with
and readlines()
with open("i_have_a_dream.txt", "r") as my_file:
content_list = my_file.readlines() #파일 전체를 list로 반환
print(type(content_list)) #Type 확인
print(content_list) #리스트 값 출력
import os
os.mkdir("log")
if not os.path.isdir("log"):
os.mkdir("log")
pathlib
모듈을 사용하여 path 를 객체로 다룸.pickle
파일은 파이썬을 위한 바이너리 파일import pickle
f = open("list.pickle", "wb")
test = [1, 2, 3, 4, 5]
pickle.dump(test, f)
f.close()
f = open("list.pickle", "rb")
test_pickle = pickle.load(f)
print(test_pickle)
f.close()
Exception
, 특정 함수의 사용Log
관리 모듈import logging
logging.debug("틀렸잖아!")
logging.info("확인해!")
logging.warning("조심해!")
logging.error("에러났어!")
logging.critical("망했다....")
import logging
logger = logging.getLogger("main") # Logger 선언
stream_hander = logging.StreamHandler() # Logger의 output 방법 선언
logger.addHandler(stream_hander) #Logger의 output 등록
logger.setLevel(logging.DEBUG)
logger.debug("틀렸잖아!!")
logger.info("확인해!!")
logger.warning("조심해!!")
logger.error("에러났어!!!")
logger.critical("망했다...")
logger.setLevel(logging.CRITICAL)
logger.debug("틀렸잖아!!")
logger.info("확인해!!")
logger.warning("조심해!!")
logger.error("에러났어!!!")
logger.critical("망했다...")
Section
, Key
, Value
값의 형태로 설정된 설정 파일을 사용import configparser
config = configparser.ConfigParser()
config.sections()
config.read('example.cfg')
config.sections()
for key in config['SectionOne']:
print(key)
config['SectionOne']["status"]
[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True
[SectionTwo]
FavoriteColor = Green
[SectionThree]
FamilyName: Johnson
argparse
를 사용import argparse
parser = argparse.ArgumentParser(description='Sum two integers.')
parser.add_argument('-a', "--a_value", dest=”A_value", help="A integers", type=int)
parser.add_argument('-b', "--b_value", dest=”B_value", help="B integers", type=int)
args = parser.parse_args()
print(args)
print(args.a)
print(args.b)
print(args.a + args.b)
CSV, 웹(Html), XML, JSON
빅데이터, 데이터분석 회사에서 인턴을 하며 크롤링, 데이터분석 을 했던 경험이 있어서 내가 아는 지식을 다시 복기하는 자세로 수강했다.
,
등에 대해 전처리 과정이 필요import csv
reader = csv.reader(f, delimiter=',', quotechar='"',quoting=csv.QUOTE_ALL)
delimiter
: 글자를 나누는 기준
lineterminator
: 줄 바꿈 기준
quotechar
: 문자열을 둘러싸는 신호 문자
quoting
: 데이터 나누는 기준이 quotechar에 의해 둘러싸인 레벨
<>
괄호 안에 둘러 쌓여 있음re
모듈을 import
하여 사용search
한개만 찾기, findall
전체 찾기