본문 바로가기
파이썬

파이썬 Python : 루프에서 모든 텍스트 파일 행 읽기

by º기록 2021. 1. 11.
반응형

한 줄씩 거대한 텍스트 파일을 읽고 싶습니다 ( "str"이있는 줄이 있으면 중지). 파일 끝에 도달했는지 확인하는 방법은 무엇입니까?

fn = 't.log'
f = open(fn, 'r')
while not _is_eof(f): ## how to check that end is reached?
    s = f.readline()
    print s
    if "str" in s: break

 

해결 방법

 

파이썬에서 EOF를 확인할 필요가 없습니다.

with open('t.ini') as f:
   for line in f:
       # For Python3, use print(line)
       print line
       if 'str' in line:
          break


파일을 다룰 때 with 키워드를 사용하는 것이 좋습니다. objects. This has the advantage that the file is properly closed after 도중에 예외가 발생하더라도 스위트는 종료됩니다.

 

참조 페이지 https://stackoverflow.com/questions/17949508

 

 

반응형

댓글