텍스트 파일의 내용을 한줄씩 반환하는 이터레이터 만들기
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)
___________결과 화면___________
sql 쿼리 명령어 요약 (3) | 2023.11.20 |
---|---|
프로그래머스 코딩연습- 파이썬편 (3) | 2023.11.20 |
이터레이터 활용 연습 -2(외부함수 이용) (1) | 2023.11.16 |
이터레이터 활용연습-1 (1) | 2023.11.16 |
도서관리 프로그램_데코레이터 함수 형태 (4) | 2023.11.14 |