[파이썬 중급문법 fin] 사용자 Exception class, 텍스트 파일 쓰기/읽기/열기, with ~ as, writelines(), readlines(), readline()

서대철·2023년 7월 12일
0
<오늘의 학습내용>
사용자 Exception class
텍스트 파일 쓰기/읽기/열기
with ~ as 문
writelines()
readlines()
readline()

33_사용자 예외 클래스

  • 예외도 ‘클래스’이기 때문에 이를 상속해서 직접 만들 수 있다.
class NoZeroException(Exception):   # user exception must take 0 as inheritance
    def __init__(self, n):    # take 'n' as input
        super().__init__(f'{n} cannot be used.')    # converts to string, and entered to parent class.

def divCal(x, y):
    if y == 0:
        raise NoZeroException(y)    # 'y' is entered as 'n' in exception class
    else:
        print(f'{n1} / {n2} = {n1/n2}')

n1 = int(input('input first number: '))
n2 = int(input('input second number: '))

try:
    divCal(n1, n2)
except NoZeroException as e:    # exception class called.
    print(e)

34-36_텍스트 파일 쓰기, 읽기, 열기

  1. open(directory, mode)
  2. read(): 기존 파일 열기 / write(): 새로운 파일 만들기, 또는 기존 파일 덮어쓰기
  3. close()
import time

lt = time.localtime()

dateStr = '[' + time.strftime('%Y-%m-%d %I:%M:%S %p') + '] '
todaySchedule = input('today\'s schedule: ')

# see here
dir = '/Users/sdc/Documents/zerobase_dataschool/pythonex/project/text/text.txt'
file = open(dir, 'w')  # inputs: 1) directory 2) type(read/write)
file.write(dateStr + todaySchedule)

file.close()

Writing 완료된 파일을 읽기

dir = '/Users/sdc/Documents/zerobase_dataschool/pythonex/project/text/text.txt'
file = open(dir, 'r')  # inputs: 1) directory 2) type(read/write)

str = file.read()

print(str)

file.close()

실습: 텍스트에서 특정 영문 string ‘Python’을 ‘파이썬’으로 변경해서 새로운 파일에 저장하기 (replace 함수 이용)

dir = '/Users/sdc/Documents/zerobase_dataschool/pythonex/project/text/about_python.txt'
file = open(dir, 'r', encoding='UTF8')

str = file.read()

print(f'Before: {str}')
new_str = str.replace('Python', '파이썬', 2)

print(f'After: {new_str}')

file.close()

newDir = '/Users/sdc/Documents/zerobase_dataschool/pythonex/project/text/about_python2.txt'
file = open(newDir, 'w', encoding='UTF8')
file.write(new_str)
file.close()

replace() 함수
Python의 replace() 함수는 문자열 내에서 지정된 하위 문자열을 다른 하위 문자열로 바꿀 수 있는 문자열 메서드입니다. 교체된 새 문자열을 반환하고 원래 문자열은 변경되지 않은 상태로 둡니다.

다음은 replace() 함수의 기본 구문입니다.

string.replace(old, new, count)
  • string: 교체를 수행하려는 원래 문자열입니다.
  • old: 바꾸려는 하위 문자열입니다.
  • new: old 항목을 대체하려는 하위 문자열입니다.
  • count(선택 사항): 이 매개변수는 교체할 최대 개수를 지정합니다. 제공되지 않으면 이전 항목이 모두 대체됩니다.

다음은 replace() 함수를 사용하는 몇 가지 예입니다.

text = "Hello, World!"
new_text = text.replace("Hello", "Hi")
print(new_text)  # Output: Hi, World!

sentence = "I like apples, apples are tasty!"
new_sentence = sentence.replace("apples", "oranges", 1)
print(new_sentence)  # Output: I like oranges, apples are tasty!

phrase = "abababab"
new_phrase = phrase.replace("a", "x")
print(new_phrase)  # Output: xbxbbxbb

첫 번째 예에서 replace() 함수는 텍스트 변수의 하위 문자열 "Hello"를 "Hi"로 교체하여 "Hi, World!"가 됩니다.

두 번째 예에서 replace() 함수는 count 매개 변수 1을 사용하여 문장 변수에서 "apples"의 첫 번째 항목을 "oranges"로 바꿉니다. 나머지 항목은 변경되지 않은 상태로 유지됩니다.

세 번째 예에서 replace() 함수는 구문 변수에서 "a"의 모든 항목을 "x"로 바꿉니다.

replace() 함수는 하나의 하위 문자열을 다른 하위 문자열로 대체하여 문자열의 특정 부분을 수정하거나 조작하려는 경우에 유용합니다. 요구 사항에 따라 문자열을 교체하고 변환하는 편리한 방법을 제공합니다.

36_텍스트 파일 열기 모드

  • ‘w’: 쓰기 전용, 파일이 있으면 덮어씌움
    • 새로운 파일 만들기에 사용
  • ‘a’: 쓰기 전용, 파일이 있으면 덧붙임
    • 주로 로그에 사용
  • ‘x’: 쓰기 전용, 파일이 있으면 에러 발생
  • ‘r’: 읽기 전용, 파일이 없으면 에러 발생

실습: 사용자가 입력한 숫자 이하의 소수를 구해서 출력 하기 (’a’모드로 파일 쓰기)

dir = '/Users/Documents/zerobase_dataschool/pythonex/project/text/'
file_name = 'prime_number2.txt'

def writePrime(n):
    file = open((dir+file_name), 'a', encoding='UTF8')
    file.write(str(n) + '\n')
    file.close()

input_num = int(input('enter an integer greater than 0: '))
for number in range(2, (input_num + 1)):
    flag = True
    for n in range(2, int(number ** 0.5) + 1):
        if number % n == 0:    # not a prime number
            flag = False
            break
    if flag:
        writePrime(number)

37_with ~ as 문

  • 파일 읽기/쓰기를 할 때 close()를 생략할 수 있음.
with open("file.txt", "a") as file:
    contents = file.write("hello python!")
    # Perform operations on the file contents

# File is automatically closed outside the 'with' block

실습: 로또 번호 출력기

import random

dir = '/Users/sdc/Documents/zerobase_dataschool/pythonex/project/text/'
file_name = 'lottery.txt'

def writeNums(list):
    for idx, num in enumerate(list):
        with open(dir + file_name, 'a') as file:
            if idx < len(list) - 2:    # put comma until one before the end (=5th num)
                file.write(str(num) + ', ')
            elif idx == len(list) - 2:    # no comma for the last num in line (=6th num)
                file.write(str(num))
            elif idx == len(list) - 1:
                file.write('\n')
                file.write(f'bonus: {num}')

    print(f'len(list): {len(list)}')
    print(f'len(list) - 2: {len(list) - 2}')
    print(f'len(list) - 1: {len(list) - 1}')

lotteryNum = random.sample(range(1, 46), 7)
print(lotteryNum)

writeNums(lotteryNum)

38_writelines()

  • 반복가능한 자료형의 데이터를 파일에 쓸 수 있습니다.
  • 반복되는 문자열을 입력으로 사용하고 각 문자열을 차례로 파일에 씁니다.
    • for 반복문을 쓰는 대신 간편하게 사용가능함.
file.writelines(iterable)   # list, tuple 등 iterable을 입력
lines = ['First line\n', 'Second line\n', 'Third line\n']

with open('file.txt', 'w') as file:
    file.writelines(lines)
  • 이 예제에는 텍스트 줄을 나타내는 세 개의 문자열이 포함된 목록 줄이 있습니다. open() 함수와 with 문을 사용하여 쓰기 모드에서 'file.txt'라는 파일을 엽니다.
  • with 블록 내에서 파일 객체의 writelines() 메서드를 사용하여 줄 목록의 내용을 파일에 씁니다. 줄 목록의 각 문자열은 파일에서 별도의 줄로 기록됩니다.
  • with 블록이 종료된 후 with 문의 동작으로 인해 파일이 자동으로 닫힙니다.
  • writelines()에 전달된 문자열에는 필요한 줄 바꿈('\n') 또는 원하는 서식이 이미 포함되어 있어야 합니다. 개행을 자동으로 추가하지 않기 때문입니다.

만약 writelines 함수 내에서 개행을 하겠다면 아래와 같이 사용이 가능합니다.

lines = ['First line', 'Second line', 'Third line']

with open('file.txt', 'w') as f:
    f.writelines(item + '\n' for item in lines)

물론, writeline()을 써서 따로 포맷팅을 하지 않고 그대로 리스트를 출력할 수도 있습니다.

lines = ['First line', 'Second line', 'Third line']

with open('file.txt', 'w') as f:
    print(lines, file=f)

38_readlines(), readline()

  • 여러 줄 읽기 vs 한 줄 읽기
  1. readlines(): 이 메서드는 파일에서 모든 줄을 읽고 문자열 목록으로 반환하는 데 사용됩니다. 파일의 각 행은 목록의 요소가 됩니다.

예를 들면 다음과 같습니다.

with open("file.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line)

이 예제에서 readlines() 메서드는 파일 객체에서 호출됩니다. 파일에서 모든 줄을 읽고 문자열 목록으로 반환합니다. 그런 다음 for 루프를 사용하여 각 줄을 인쇄합니다.

  1. readline(): 이 메서드는 파일에서 한 줄을 읽고 문자열로 반환하는 데 사용됩니다. readline()이 호출될 때마다 파일에서 다음 줄을 읽습니다.

예를 들면 다음과 같습니다.

with open("file.txt", "r") as file:
    line1 = file.readline()
    line2 = file.readline()
    print(line1)
    print(line2)

## 또는,

with open("file.txt", "r") as file:
	    line = file.readline()
			
			while line != ""
			    print(line, end='')
					line = file.readline()

readlines() 및 readline() 둘 다 파일에서 데이터를 읽으려고 할 때 사용됩니다. readlines()는 일반적으로 한 번에 모든 줄을 읽고 전체 줄 집합에서 작업을 수행하려는 경우에 사용됩니다. readline()은 파일을 한 줄씩 읽고 각 줄을 개별적으로 처리하려는 경우에 유용합니다.

open() 함수를 사용하여 적절한 모드(읽기의 경우 "r")에서 파일을 열고 with 문을 사용하여 읽은 후 자동으로 파일을 닫습니다.

실습: 텍스트 파일에 저장된 과목과 점수명을 읽어 딕셔너리에 저장하기

dir = '/Users/sdc/Documents/zerobase_dataschool/pythonex/project/text/'
file_name = 'scores.txt'

score_dict = {}

with open(dir+file_name,'r') as f:
    line = f.readline()

    while line != '':
        print(line, end='')
        tempList = line.split(':')
        score_dict[tempList[0]] = int(tempList[1].strip('\n'))
        line = f.readline()

print('\n')
print(f'scoreDictionary: {score_dict}')

0개의 댓글