TIL

사전캠프 16일차

ds3hfj 2024. 11. 11. 22:00

파일 처리하기

 

열고

file = open("example.txt","r") #읽기 모드로 파일 열기
#파일 처리 작업 수행
file.close()

닫고

읽고

with open("example.txt","r") as file:
          # 파일 처리 작업 수행
          content = file.read()

with open은 클로즈 안해도 됨

file_object = open("파일이름", "모드(r,w,a,b)") b는 바이너리 모드- 이진 파일을 읽거나 쓸때 사용하며

rb, wb 처럼 다른 모드와 함께 사용

 

read 메서드 예시

with open("example.txt","r") as file:
          # 파일 처리 작업 수행
          content = file.read()
          print(content)

readline 메서드 예시

with open("example.txt","r") as file:
    line = file.readline()
    print(line)

readlines 메서드 예시

with open("example.txt","r") as file:
    lines= file.readlines()
    for line in lines:
        print(line.strip())#각 줄의 공백을 제거하고 출력

      

write 메서드 예시

with open("output.txt", "w") as file:

    file.write("이것은 새로운 파일에 쓰여진 내용입니다.")

 

writelines 메서드 예시

 

lines = ["첫 번째 줄\n", "두 번째 줄\n", "세 번째 줄\n"]

with open("sample.txt", "w") as file:
    file.writelines(lines)

첫번째줄

두번째줄

세번째줄

 

이터레이터

 

numbers = [1, 2, 3, 4, 5]  # 리스트는 반복 가능한 객체
for num in numbers:
    print(num)

 

numbers = [1, 2, 3]
iterator = iter(numbers)  # 리스트로부터 이터레이터 생성

print(next(iterator))  # 1
print(next(iterator))  # 2
print(next(iterator))  # 3

 

class MyIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index < len(self.data):
            result = self.data[self.index]
            self.index += 1
            return result
        else:
            raise StopIteration

# 이터레이터 사용
my_iter = MyIterator([1, 2, 3])
for item in my_iter:
    print(item)

 

#제너레이터 함수

def simple_generator():
    yield 1
    yield 2
    yield 3

gen = simple_generator()

print(next(gen))  # 1
print(next(gen))  # 2
print(next(gen))  # 3

1

2

3

제너레이터 사용 예시

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

# 피보나치 수열 생성
for num in fibonacci(10):
    print(num)

0

1

1

2

3

5

8

13

21

34

listtest=[x*x for x in range(5)]
print(listtest)

[0, 1, 4, 9, 16]

gen_exp = (x * x for x in range(5))

for num in gen_exp:
    print(num)

0
1
4
9
16

yield: 제너레이터 함수에서 값을 반환하고, 함수의 실행 상태를 유지하며 다음 호출 시 재개됩니다.

 

 데코레이터(Decorator)는 함수나 메서드를 변경하지 않고, 추가적인 기능을 쉽게 추가할 수 있는 방법

def decorator_function(original_function):
    def wrapper_function(*args, **kwargs):
        # 추가할 기능
        print("추가 기능 실행 전")
        result = original_function(*args, **kwargs)
        print("추가 기능 실행 후")
        return result
    return wrapper_function

@decorator_function
def sample_function():
    print("원래 함수 실행")

# 함수 호출
sample_function()

데코레이터 체이닝구조

 

데코레이터 여러개인 경우 안쪽에서 밖으로(가까운 순으로) 적용

 

컨텍스트 매니저

class MyContextManager:
    def __enter__(self):
        print("리소스를 획득합니다.")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("리소스를 정리합니다.")

# 컨텍스트 매니저 사용
with MyContextManager():
    print("작업 수행 중...")

 

컨텍스트 매니저는 with 구문을 통해 사용되며, 코드의 시작과 끝에서 자동으로 설정 및 정리 작업

 

with 구문의 기본 구조(리소스 획득 , 정리 자동으로 처리)

with 컨텍스트매니저 as 변수:

    # 작업 수행

컨텍스트 매니저 

1. 파일처리 - 파일 열고 닫는 작업 안전하게 처리

2. 데이터베이스 연결 - 데이터 베이스 연결 열고, 작업후 자동으로 연결 종료

3. 락 관리 - 멀티스레팅 환경에서 락 획득, 작업이 끝나면 자동으로 락 해제

'TIL' 카테고리의 다른 글

사전캠프 24일차  (1) 2024.11.21
사전캠프 23일차  (0) 2024.11.21
사전캠프 15일차  (1) 2024.11.08
사전캠프 14일차  (1) 2024.11.07
사전캠프 13일차  (0) 2024.11.06