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)
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()
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()
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)
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)
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()
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}')
💻 출처 : 제로베이스 데이터 취업 스쿨