Among Us - Orange Crewmate

상세 컨텐츠

본문 제목

이터레이터 활용 연습-3(파일 불러오기)

코딩연습

by nick wilde 2023. 11. 16. 17:03

본문

반응형

텍스트 파일의 내용을 한줄씩 반환하는 이터레이터 만들기

 

class FileLineIterator :
    def __init__(self, file_path) :
        self.file_path = file_path
        self.file = open(file_path, "r", encoding="utf-8")

    def __iter__(self) :
        return self

    def __next__(self):
        # print("#1 --------------------")
        # ## readLine() : 파일 정보중에 줄 하나 가지고옴
        # - 최초 이후부터는 다음 줄이 있는 자동으로 체크 후 가지고 옴
        # - 다음 줄이 없으면 안가져옴
        line = self.file.readline()
        # print(f'#2 : line = {line}')
        if line :
            # print(f'#3 : line = {line}')
            return line.strip()
            ###strip()은 공백을 제거해주는 역할 수행
        else :
            self.file.close()
            raise StopAsyncIteration

 

 

### 이터레이터 클래스 생성하기
file_path = "./04_example.txt"
file_iter = FileLineIterator(file_path)

 

for line in file_iter :
    print(line)

 

 

___________결과 화면___________

반응형

관련글 더보기