파이썬 중급_(예외, 텍스트)

TaeHwi Kang·2022년 9월 15일
0

1. 예외

  • 문법적인 문제는 없으나 실행 중 발생하는 예상하지 못한 문제
  • 예외 관련 클래스는 Exception 클래스를 상속한다.

2. 예외 처리

  • 예상하지 못한 예외가 프로그램 전체에 영향이 없도록 처리함
    1) try ~ except
#예외 발생 예상 구문을 try ~ except로 감싼다
nums = []
n = 1
while n < 6:

    try:
        num = int(input('number : '))

    except:
        print('예외 발생')
        continue
    nums.append(num)
    n += 1

2) try ~ except ~ else

#else : 예외가 발생하지 않은 경우 실행하는 구문이다
nums = []
n = 1
while n < 6:

    try:
        num = int(input('number : '))

    except:
        print('예외 발생')
        continue

    else:
        if num % 2 == 0:
            nums.append(num)
            n += 1

        else:
            print('홀수, 다시입력하세요')
            continue

3) finally

#예외 발생과 상관없이 항상 실행한다
eveList = []; oddList = []; floatList = []; dataList = []

n = 1
while n < 6:
    try:
        data = input('input data : ')
        floatNum = float(data)

    except:
        print('에러 발생')
        print('다시입력하세요')
        continue

    else:
        if floatNum - int(floatNum) != 0:
            print('floatList')
            floatList.append(floatNum)

        else:
            if floatNum % 2 == 0:
                print('eveList')
                eveList.append(int(floatNum))

            else:
                print('oddList')
                oddList.append(int(floatNum))
        n += 1

    #무조건 실행	
    finally: 
        dataList.append(data)

3. Exception 클래스

1) Exception : 예외 담당 클래스
2) raise : raise 키워드를 이용하면 예외를 발생시킬 수 있다.

def divCalculator(n1,n2):

    if n2 != 0:
        print(f'{n1 / n2}')

    else:
    	# raise 키워드를 이용하면 예외를 발생시킬수있다
        raise Exception('0으로 나눕지 못합니다')

num1 = int(input("숫자입력 : "))
num2 = int(input("숫자입력 : "))

try:
    divCalculator(num1,num2)
    
#excetion class 예외담당 클래스
except Exception as e:
    print(f'{e}')

4. 사용자 예외 클래스

  • Exception 클래스를 상속해서 사용자 예외 클래스를 만들 수 있다.
class PasswordLengthShortException(Exception):
    def __init__(self, str):
        super().__init__(f'{str}: 길이 5 미만')

class PasswordLengthLongException(Exception):
    def __init__(self, str):
        super().__init__(f'{str}: 길이 10 초과')

class PasswordWrongException(Exception):
    def __init__(self, str):
        super().__init__(f'{str}: 잘못된 비밀번호 ')

adminPW = input('input admin password')

try:
    if len(adminPW) < 5:
        raise PasswordLengthShortException(adminPW)

    elif len(adminPW) > 10:
        raise PasswordLengthLongException(adminPW)

    elif adminPW != 'admin1234':
        raise PasswordWrongException(adminPW)

except PasswordLengthShortException as e1:
    print(e1)

except PasswordLengthLongException as e2:
    print(e2)

except PasswordWrongException as e3:
    print(e3)

5. 텍스트파일 쓰기

  • 기본함수 : open(), read(), write(), close()
#파일쓰기
file = open('C:/pythonTXT/test.txt','w')

strCnt = file.write('hello ptython')
print(f'{strCnt}')

file.close()

#텍스트 파일에서 ‘Python’을 ‘파이썬’으로 변경해서 파일에 다시 저장
file = open('C:/pythonTXT/test.txt','r', encoding='UTF8')

str = file.read()
print(f'{str}')

file.close()

#문자 교채, 앞에서 부터 몇번쨰까지
str.replace('python', '파이썬', 2) 
print(f'{str}')

file = open('C:/pythonTXT/test.txt','w')
file.write(str)
file.close()

#open() 파일 모드
'w' 쓰기전용_파일이 있으면 덮어씌움
'a' 쓰기전용_파일이 있으면 덧붙임
'x' 쓰기전용_파일이 있으면 에러발생
'r' 읽기전용_파일이 없으면 에러발생

6. with ~ as문

with ~ as문을 이용하면 파일 닫기 close()를 생략할수있다

file = open(url + 'test.txt', 'a')
file.write('파일 쓰기')
file.close()

with open(url + 'test.txt', 'a') as f:
    f.write("파일쓰기")

file = open(url + 'test.txt', 'r')
file.read()
file.close()

with open(url + 'test.txt', 'r') as f:
    f.read()

7. writelines()

writelines()는 리스트(List) 또는 튜플 데이터를 파일에 쓰기 위한 함수

languages = ['python', 'java', 'c/c++']

uri = 'C:/pythonTXT'
for item in languages:
	with open(uri + 'languages.txt', 'a') as f:
	f.wirte(item)
	f.wirte(\n)

with open(uri + 'language.txt', 'a') as f:
	f.writelines(languages)

8. readlines(), readline()

1) readlines() : 파일의 모든 데이터를 읽어서 리스트 형태로 반환한다.

uri = 'C:/pythonTXT'

with open(uri + 'languages.txt', 'r') as f:
	lanList = f.readlines()

print(f'{lanList}')         -->  ['python', 'java', 'c/c++']
print(f'{type(lanList)}')  --> <Class 'list'>

2) readline() : 한 행을 읽어서 문자열로 반환 한다.

uri = 'C:/pythonTXT'

with open(uri + 'languages.txt', 'r') as f:
	line = f.readline()

	while line != '':
	print(f'{line}', end ='')
	line = f.readline()

-->
python
java
c/c++
profile
스터디 노트

0개의 댓글