ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Exception/File/Log Handling
    BoostCourse 2023. 1. 2. 23:55

    Exception Handling

    try:
        예외 발생 가능 코드
    except <Exception Type>:
        예외 발생 시 대응하는 코드

    예시(try ~ except)

    for i in range(10):
        try:
            print(10/i)
        except ZeroDivisionError:
            print("Not divided by 0")
        except Exception as e:
            print(e)

    예시 2 (try ~ except ~ else)

    for i in range(10):
        try:
            result = 10 // i
        except ZeroDivisionError:
            print("Not divided by 0")
        else:
            print(result)

    예시 3 (try ~ except ~ finally)

    for i in range(10):
        try:
            print(10 // i)
        except ZeroDivisionError:
            print("Not divided by 0")
        finally:
            print("종료되었습니다")

    예시 4 (raise)

    raise <Exception Type>(예외정보)
    while True:
        value = input("변환할 정수 값을 입력해주세요 ")
        for digit in value:
            if digit not in "0123456789":
                raise ValueError("숫자값을 입력하지 않으셨습니다")
            print("정수값으로 변환된 숫자 -", int(value))

    예시 5 (assert)

    assert 예외조건
    def get_binary_number(decimal_number: int):
        assert isinstance(decimal_number, int)
        return bin(decimal_number)

    ** isinstance() function returns True if the specified object is of the specified type, otherwise Flase.


    File Handling

    - 기본적인 파일로 Text 파일과 Binary 파일이 있다.

    - Text 파일은 메모장으로 열면 내용 확인이 가능하다.

    f = open("파일이름", "접근 모드")
    f.close()

    Read

    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 = my_file.read()
        print(contents)

    한 줄씩 읽어 List Type으로 반환하기

    with open("i_have_a_dream.txt", "r") as my_file:
        content_list = my_file.readlines()
        print(content_list)

    실행 시 한 줄씩 읽어오기

    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

    단어 통계 정보 산출

    with open("i_have_a_dream.txt", "r") as my_file:
        contents = my_file.read()
        word_list = contents.split(" ")
        line_list = contents.split("\n")
    
    print("Total Number of Characters: %d" % (len(contents)))
    print("Total Number of Words: %d" % (len(word_list)))
    print("Total Number of Lines: %d" % (len(line_list)))

    Write

    mode는 "w", encoding="utf8" or "CP949"

    f = open("count_log.txt", mode="w", encoding="utf8")
    for i in range(1, 11):
        data = "{0}번째 줄입니다.\n".format(i)
        f.write(data)
    f.close()
    with open("count_log.txt", "a", encoding="utf8") as f:
        for i in range(1, 11):
            data = "%d번째 줄입니다.\n" % i
            f.write(data)

    ** directory keywords **

    import os
    if not os.path.isdir("folder_name"):
        os.mkdir("folder_name")
    
    import pathlib
    cwd = pathlib.Path.cwd() # current working directory
    list(cwd.parents)
    list(cwd.glob("*"))

    Pickle

    파이썬의 객체를 영속화하는 Built-in 객체

    import pickle
    
    f = open("list.pickle", "wb") # wirte_binary mode
    test = [1, 2, 3, 4, 5]
    pickle.dump(test, f)
    f.close()
    
    # 이후 test 값을 언제든지 불러올 수 있게 된다.
    
    f = open("list.pickle", "rb")
    test_pickle = pickle.load(f)
    print(test_pickle)
    f.close()

    Logging Handling

    콘솔 화면에 출력하기, 파일에 남기기, DB에 남기기 등등

    DEBUG > INFO > WARNING > ERROR > CRITICAL

    import logging
    
    logger = logging.getLogger("main")
    logging.basicConfig(level=logging.DEBUG)
    logger.setLevel(logging.INFO)
    
    str_handler = logging.FileHandler("my.log", mode="w", encoding="utf8")
    logger.addHandler(str_handler)
    
    logging.debug("debug")
    logging.info("info")
    logging.warning("warning")
    logging.error("error")
    logging.critical("critical")

    저장이 안 되는데 추후 확인하겠다.

     

    key words: configparser, argparser

    configparser: ini 파일에 key: value 형태로 값을 저장하고 추후 호출한다.

    argparser: 프로그램에 필요한 인자를 사용자가 쉽게 입력하도록 도와준다.

     

    Logging FormmaterLog 결과값의 format을 지정해준다.

    formatter = logging.Formatter('%(asctime)s %(levelname)s %(process)d %(message)s')

     

    'BoostCourse' 카테고리의 다른 글

    벡터가 뭐에요?  (0) 2023.01.05
    Numpy  (1) 2023.01.05
    Module and Project  (0) 2023.01.02
    Python Object Oriented Programming  (0) 2022.12.31
    데이터 구조(Data Structure)  (0) 2022.12.29

    댓글

Designed by Tistory.