스터디노트(Python 중급8~9)

zoe·2023년 3월 10일
0

💡 사용자 예외 클래스

  • Exception 클래스를 상속해서 사용자 예외 클래스를 만들 수 있다
class NotUseZeroException(Exception):

    def __init__(self, n):
        super().__init__(f'{n}은 사용할 수 없습니다!') # ★★★★★


def divCalculator(num1, num2):

    if num2 == 0:
        raise NotUseZeroException(num2)
    else:
        print(f'{num1} / {num2} = {num1 / num2}')


num1 = int(input('input number : '))
num2 = int(input('input number : '))

try:
    divCalculator(num1, num2)
except NotUseZeroException as e:
        print(e)
  • 실습

💡 관리자 암호를 입력하고 다음 상태에 따라 예외 처리하는 예외 클래스를 생성

# 관리자 암호를 입력하고 다음 상태에 따라 예외 처리하는 예외 클래스를 생성

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)
    elif adminPw == 'admin1234':
        print('빙고!')
except PasswordLengthShortException as e1:
    print(e1)
except PassWordLengthLongException as e2:
    print(e2)
except PasswordWrongException as e3:
    print(e3)

💡 텍스트 파일 쓰기

  • open() : 파일 열기
    - 파일이 없으면 새로 파일이 생성, 기존 파일이 있을 경우에는 덮어쓰기가 됨
  • read() : 파일 문자열 읽기
  • write() : 쓰기
  • close() : 파일 닫기
  • 💡 time.strftime() : 명시적 포맷 문자열로 제어된 시간을 나타내는 문자열을 생성 (출처 : datetime, strftime 정보 출처)
    - import time 모듈을 이용
    - ex) time.strftime('%Y-%m-%d %H:%M:%S %p') → 2023-03-10 16:13:40 PM
    • %H : 24시 중 현재 시간, %I : 오전 오후 12시 중 시간
file = open('C:/Users/파이썬 중급 pythontxt/test.txt','w') # 경로 수정 필요
# 파일이 없으면 새로 생성됨
# 파일이 있으면 덮어쓰기가 됨
strCnt = file.write('hello PYTHON')
print(f'strCnt : {strCnt}')
file.close()
  • 실습

💡 다음과 같이 시스템 시간과 일정을 텍스트 파일에 작성

# 다음과 같이 시스템 시간과 일정을 텍스트 파일에 작성

import time

lt = time.localtime()
# dateStr = '[ ' + str(lt.tm_year) + '년 ' + str(lt.tm_mon) + '월 ' \
#          + str(lt.tm_mday) + '일 ]'
dateStr = '[ ' + time.strftime('%Y-%m-%d %I:%M:%S %p') + ' ]'

todaySchedule = input('오늘 일정 : ')

file = open('C:/Users/파이썬 중급 pythontxt/test.txt','w') # 경로 수정 필요
file.write(dateStr + todaySchedule)
file.close()

텍스트 파일 쓰기

  • read() : 파일 문자열 읽기
    - UnicodeDecodeError: 'cp949' codec can't decode byte 0xec in position 7: illegal multibyte sequence
    • 인코딩 이슈 open('파일경로','r', encoding='UTF8')로 읽으면 에러가 나지 않음
  • 💡 replace('단어1', '단어2', n) : 앞부터 n개의 '단어1'를 '단어2'로 바꿔줌, n개를 입력하지 않으면 전체 '단어1'을 '단어2'로 변경
file = open('C:/Users/파이썬 중급 pythontxt/test.txt','r') # 경로 수정 필요
str = file.read()
print(str)
  • 실습

💡 다음 텍스트 파일에서 ‘Python’을 ‘파이썬’으로 변경해서 파일에 다시 저장

# 다음 텍스트 파일에서 ‘Python’을 ‘파이썬’으로 변경해서 파일에 다시 저장

file = open('C:/Users/파이썬 중급 pythontxt/about_python.txt','r',encoding='cp949') # 경로 수정 필요
# UnicodeDecodeError: 'cp949' codec can't decode byte 0xec in position 7: illegal multibyte sequence
# 인코딩 이슈 open('파일경로','r', encoding='UTF8')로 읽으면 에러가 나지 않음
str = file.read()
print(f'str : {str}')

str = str.replace('Python','파이썬',2)
# replace('단어1', '단어2', n) **: 앞부터 n개의 '단어1'를 '단어2'로 바꿔줌, n개를 입력하지 않으면 전체 '단어1'을 '단어2'로 변경

print(f'str : {str}')

file = open('C:/Users/파이썬 중급 pythontxt/about_python.txt','w') # 경로 수정 필요
file.write(str)
file.close()

💡 텍스트 파일 열기

  • 파일 모드는 파일을 어떤 목적으로 open할지 정한다
    - 'w' : 쓰기 전용(파일이 있으면 덮어씌움)
    - 'a' : 쓰기 전용(파일이 있으면 덧붙임) (ex: 로그 기록...)
    - 'x' : 쓰기 전용(파일이 있으면 에러발생)
    • 'r' : 읽기 전용(파일이 없으면 에러 발생)
url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요

# 'w' 파일 모드

# file = open(url + '/hello.txt','w')
# file.write('hello python!')
# file.close()

# 'a' 파일 모드
# file = open(url + '/hello.txt','a')
# file.write('\nNice to meet you!')
# file.close()

# 'x' 파일 모드
# file = open(url + '/hello.txt','x')
# file.write('\nNice to meet you!')
# file.close()

# file = open(url + '/hello_01.txt','x')
# file.write('\nNice to meet you!')
# file.close()

# 'r' 파일 모드
file = open(url + '/hello_01.txt','r')
str = file.read()
print(str)
file.close()
  • 실습

💡 사용자가 입력한 숫자에 대한 소수를 구하고 이를 파일에 작성

# 사용자가 입력한 숫자에 대한 소수를 구하고 이를 파일에 작성

url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요

def writePrimeNumber(n):
    file = open(url + '/prime_number.txt','a')
    file.write(str(n)) # ★
    file.write('\n') # ★
    file.close()

inputNumber = int(input('0보다 큰 정수 입력 : '))
for number in range(1, inputNumber + 1):
    flag = True
    for i in range(2, number): # ★★★★★ number를 2 ~ number-1까지 나누며 나머지를 구함
        if number % i == 0:
            flag = False
            break # ★★★★★

    if (flag):
        writePrimeNumber(number)

💡 with ~ as문

  • with ~ as문 : 파일 닫기(close) 생략 가능
url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요

with open(url + '/5_037.txt','a') as f:
    f.write('python study!')

with open(url + '/5_037.txt','r') as f:
    print(f.read())
  • 실습

💡 로또 번호 생성기 프로그램을 만들고 파일에 번호를 출력

# 로또 번호 생성기 프로그램을 만들고 파일에 번호를 출력

import random

url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요

def writeNumbers(nums):
    for idx, num in enumerate(nums):
        with open(url + '/lotto.txt','a') as f :
            if idx < (len(nums) - 2) :
                # ★ 7개의 숫자를 뽑았다고 할 때, len(nums) - 2 → 7 - 5  = 5개,
                # 0, 1, 2, 3, 4
                f.write(str(num) + ', ')
            elif idx == (len(nums) - 2) : # ★ 5번째
                f.write(str(num))
            elif idx == (len(nums) - 1): # ★ 6번째
                f.write('\n')
                f.write('bonus : ' + str(num))
                f.write('\n')

rNums = random.sample(range(1, 46), 7)
print(f'rNums : {rNums}')
writeNumbers(rNums)

💡 writelines()

  • writelines() : 리스트(List) 또는 튜플 데이터를 파일에 쓰기 위한 함수 ( ※ 반복적으로 입력 )
url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요

#languages = ('c/c++', 'java', 'c#', 'python', 'javascript') # 튜플
# languages = ['c/c++', 'java', 'c#', 'python', 'javascript'] # 리스트
# for item in languages:
#     with open(url + '/languages.txt','a') as f:
#         f.write(item)
#         f.write('\n')
languages = ['c/c++', 'java', 'c#', 'python', 'javascript']
url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요
with open(url + '/language.txt', 'a') as f:
    #f.writelines(languages)
    f.writelines(item + '\n' for item in languages) #줄바꿈

with open(url + '/language.txt','r') as f:
    print(f.read())
  • 실습

💡 딕셔너리에 저장된 과목별 점수를 파일에 저장하는 코드를 작성 ( + 💡 딕셔너리 전체를 통째로 저장)

# 딕셔너리에 저장된 과목별 점수를 파일에 저장하는 코드를 작성

scoreDic = {'kor':85, 'eng':90, 'mat':92, 'sci':79, 'his':82}

url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요

for key in scoreDic.keys():
    with open(url + '/scoreDic.txt','a') as f:
        f.write(key + '\t : ' + str(scoreDic[key]) + '\n') # ★★★★★
# 통째로 파일 저장
scoreDic = {'kor':85, 'eng':90, 'mat':92, 'sci':79, 'his':82}

url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요

with open(url + '/scores.txt','a') as f:
    print(scoreDic,file=f) # 딕셔너리, 리스트 등 통째로 파일에 저장 가능

💡 readlines(), readline()

  • readlines() : 파일의 모든 데이터를 읽어서 리스트 형태로 반환 (여러 줄 읽기)
  • readline() : 한 행을 읽어서 문자열로 반환 (한 줄씩 읽기)
  • split() : () 안의 입력한 글자 기준으로 문자열 나눔
  • strip() : () 안의 형식 제거
# readlines()
url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요

with open(url + '/lans.txt','r') as f:
    lanList = f.readlines()

print(f'lanList : {lanList}')
print(f'lanList type : {type(lanList)}')
# readline()
url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요

with open(url + '/lans.txt','r') as f:
    line = f.readline()

    while line != '':
        print(f'readline() : {line}', end='') # print 실행 후 줄바꿈을 함, print 줄바꿈을 없애고자 할 경우 end='' 사용
        line = f.readline()

💡 파일에 저장된 과목별 점수를 파이썬에서 읽어, 딕셔너리에 저장하는 코드를 생성

# 파일에 저장된 과목별 점수를 파이썬에서 읽어, 딕셔너리에 저장하는 코드를 생성

url = 'C:/Users/파이썬 중급 pythontxt' # 경로 수정 필요

scoreDic = {}

with open(url + '/scoreDic.txt','r') as f:
    line = f.readline()

    tempList = line.split(':') # split() : () 안의 입력한 글자 기준으로 문자열 나눔
        #print(tempList)
        print(tempList[0].replace('\t ',''))
        #print(tempList[1].lstrip().replace('\n','')) #lstrip() : 왼쪽 공백제거
        print(tempList[1].lstrip().replace('\n', '')) #strip() : () 안의 형식 제거
        #scoreDic[tempList[0].replace('\t ','')] = int(tempList[1].lstrip().replace('\n','')) # ★★★
        scoreDic[tempList[0].replace('\t ', '')] = int(tempList[1].lstrip().strip('\n'))  # ★★★


        line = f.readline()

print(f'scoreDic : {scoreDic}')

💻 출처 : 제로베이스 데이터 취업 스쿨

profile
#데이터분석 #퍼포먼스마케팅 #데이터 #디지털마케팅

0개의 댓글