[Python 중급 문제풀이]
텍스트 파일(01-05)
텍스트 파일(01) _텍스트 파일 읽기/쓰기 프로그래밍
회원 계정별 텍스트 파일을 생성한 후 회원 본인 파일에 '한 줄 일기'를 쓰고 읽는 프로그램을 만들어보자.
import time def writeDiary(u, f, d): lt = time.localtime() timeStr = time.strftime('%Y-%m-%d %I:%M:%S %p', lt) filePath = u + f with open(filePath, 'a') as f: f.write(f'[{timeStr}] {d}\n') def readDiary(u, f): lt = time.localtime() timeStr = time.strftime('%Y-%m-%d %I:%M:%S %p', lt) filePath = u + f datas = [] with open(filePath, 'r') as f: datas = f.readlines() return datas import diary members = {} uri = '/Users/jeongsuyeon/pythonTxt/' def printMembers(): for m in members.keys(): print(f'ID: {m} \t PW: {members[m]}') while True: selectNum = int(input('1.회원가입,\t 2.한줄일기쓰기,\t 3.한줄일기보기,\t 4.종료 ')) if(selectNum == 1): mId = input('input ID: ') mPw = input('input PW: ') members[mId] = mPw printMembers() elif(selectNum == 2): mId = input('input ID: ') mPw = input('input PW: ') if mId in members and members[mId] == mPw: print('login success!!') fileName = 'myDaiary_' + mId + '.txt' data = input('오늘 하루 인상 깊은 일을 기록하세요. ') diary.writeDiary(uri, fileName, data) else: print('login fail!!') printMembers() elif (selectNum == 3): mId = input('input ID: ') mPw = input('input PW: ') if mId in members and members[mId] == mPw: print('login success!!') fileName = 'myDaiary_' + mId + '.txt' datas = diary.readDiary(uri, fileName) for d in datas: print(d, end='') else: print('login fail!!') printMembers() elif (selectNum == 4): print('Bye~') break
텍스트 파일(02) _텍스트 파일 읽기/쓰기 프로그래밍
텍스트 파일에 수입과 지출을 기록하는 가계부를 만들어보자.
import time def getTime(): lt=time.localtime() st=time.strftime('%Y-%m-%d %H:%M:%S') return st while True: selectNumber=int(input('1.입금 2.출금 3.종료 :')) if selectNumber==1: money=int(input('입금액 입력: ')) with open ('/Users/jeongsuyeon/pythonTxt/money.txt','r') as f: m=f.read() with open ('/Users/jeongsuyeon/pythonTxt/money.txt','w') as f: f.write(str(int(m)+money)) memo=input('입금 내역 입력: ') with open ('/Users/jeongsuyeon/pythonTxt/pocketMoney.txt','a') as f: f.write('-----------------------------------------------------------\n') f.write(f'{getTime()} \n') f.write(f'[입금] {memo} : {str(money)}원\n') f.write(f'[잔액] {str(int(m)+money)}원\n') print('입금 완료!!') print(f'기존 잔액 : {m}') print(f'입금 후 잔액 : {int(m)+money}') elif selectNumber==2: money=int(input('출금액 입력:')) with open('/Users/jeongsuyeon/pythonTxt/money.txt','r') as f: m=f.read() with open('/Users/jeongsuyeon/pythonTxt/money.txt','w') as f: f.write(str(int(m)-money)) memo=input('출금 내역 입력: ') with open('/Users/jeongsuyeon/pythonTxt/pocketMoney.txt','a') as f: f.write('-----------------------------------------------------------\n') f.write(f'{getTime()} \n') f.write(f'[출금] {memo} : {str(money)}원\n') f.write(f'[잔액] {str(int(m) - money)}원\n') print('출금 완료!!') print(f'기존 잔액 : {m}') print(f'출금 후 잔액 : {int(m) - money}') elif selectNumber==3: print('Bye~') break else: print('잘못 입력하셨습니다.')
텍스트 파일(03) _텍스트 파일 읽기/쓰기 프로그래밍
사용자가 입력한 숫자의 약수를 텍스트 파일에 기록해 보자.
사용자가 입력한 숫자까지의 소수를 텍스트 파일에 기록해 보자.
#약수 inputNumber=int(input('0보다 큰 정수 입력 :')) divisor=[] for number in range(1,(inputNumber+1)): if inputNumber % number ==0: divisor.append(number) if len(divisor) >0: try: with open('/Users/jeongsuyeon/pythonTxt/divisor.txt','a') as f: f.write(f'{inputNumber}의 약수 :') f.write(f'{divisor}\n') except Exception as e: print(e) else: print('divisor write complete') # 소수 inputNumber=int(input('0보다 큰 정수 입력 :')) prime=[] for number in range(2,(inputNumber+1)): flag=True for n in range(2,number): if number %n==0: flag=False break if (flag): prime.append(number) if len(prime) >0: try: with open('/Users/jeongsuyeon/pythonTxt/prime.txt','a') as f: f.write(f'{inputNumber} 까지의 소수 :') f.write(f'{prime}\n') except Exception as e: print(e) else: print('prime write complete')
텍스트 파일(04) _텍스트 파일 읽기/쓰기 프로그래밍
두 개의 수를 입력하면 공약수를 텍스트 파일에 작성해보자.
두 개의 수를 입력하면 최대공약수를 텍스트 파일에 작성해보자.
#공약수 num1=int(input('1보다 큰 정수 입력 :')) num2=int(input('1보다 큰 정수 입력 :')) common=[] for i in range(1,(num1+1)): if num1 % i ==0 and num2 % i==0: common.append(i) if len(common)>0: try: with open('/Users/jeongsuyeon/pythonTxt/common.txt','a') as f: f.write(f' {num1}와 {num2}의 공약수 :') f.write(f'{common}\n') except Exception as e: print(e) else: print('common factor write complete!') # 최대 공약수 num1 = int(input('1보다 큰 정수 입력: ')) num2 = int(input('1보다 큰 정수 입력: ')) maxComNum = 0 for i in range(1, (num1 + 1)): if num1 % i == 0 and num2 % i == 0: maxNum = i try: with open('/Users/jeongsuyeon/pythonTxt/maxComNum.txt','a') as f: f.write(f'{num1}와 {num2}의 최대공약수: {maxNum}\n') except Exception as e: print(e) else: print('max common factor write complete!')
텍스트 파일(05) _텍스트 파일 읽기/쓰기 프로그래밍
섬마을에 과일, 생선, 야채를 판매하는 배가 다음 주기로 입항한다고 할 때, 모든 배가 입항하는 날짜를 텍스트 파일에 기록해보자.
(첫 입항일은 2021년 1월 1일 오전 10시로 한다.)
ship1 = 3; ship2 = 4; ship3 = 5 maxDay = 0 for i in range(1, (ship1 + 1)): if ship1 % i == 0 and ship2 % i == 0: maxDay = i # print('최대공약수: {}'.format(maxDay)) minDay = (ship1 * ship2) // maxDay # print('{}, {}의 최소공배수: {}'.format(ship1, ship2, minDay)) newDay = minDay for i in range(1, (newDay + 1)): if newDay % i == 0 and ship3 % i == 0: maxDay = i # print('최대공약수: {}'.format(maxDay)) minDay = (newDay * ship3) // maxDay # print('{}, {}, {}의 최소공배수: {}'.format(ship1, ship2, ship3, minDay)) # print('{}일마다 모든 선박이 입항합니다.'.format(minDay)) from datetime import datetime from datetime import timedelta n = 1 baseTime = datetime(2021, 1, 1, 10, 0, 0) # baseTime = datetime.now() # print(f'2021년 모든 선박 입항일: {baseTime}') with open('/Users/jeongsuyeon/pythonTxt/arrive.txt','a') as f: f.write(f'2021년 모든 선박 입항일\n') f.write(f'{baseTime}\n') nextTime = baseTime + timedelta(days=minDay) while True: # print(f'2021년 모든 선박 입항일: {nextTime}') with open('/Users/jeongsuyeon/pythonTxt/arrive.txt','a') as f: f.write(f'{nextTime}\n') nextTime = nextTime + timedelta(days=minDay) if nextTime.year > 2021: break