2017-10-04 9 views
0

저는 파이썬을 처음 사용하고 파일에서 모든 내용을 읽으려고합니다. 첫 번째 줄에 특정 패턴이 들어 있으면 {두 번째 줄, 파일 끝}에서 읽으려고합니다. pattern이 없으면 전체 파일을 읽고 싶습니다. 여기에 제가 작성한 코드가 있습니다. 이 파일에는 1 행에 '로그'가 있고 다음 행에는 일부 문자열이 있습니다.readline을 사용하여 첫 번째 줄을 일치시키고 패턴이 존재하지 않으면 seek을 사용하여 파일을 읽으십시오.

with open('1.txt') as f: 
    if 'Logs' in f.readline(): 
     print f.readlines() 
    else: 
     f.seek(0) 
     print f.readlines() 

코드가 제대로 작동합니다. 올바른 방법인가요? 아니면 개선이 필요한지 궁금합니다.

답변

0

첫 번째 줄은 "로그"가 아닌 경우 단지 조건부 인쇄 추구 할 필요가 없습니다 :

with open('1.txt') as f: 
    line = f.readline() 
    if "Logs" not in line: 
     print line 
    print f.readlines() # read the rest of the lines 

여기에 메모리에 전체 파일을 읽지 않습니다 대체 패턴 (항상 HUST 수 있어요^H^H 확장 성^H^Hthinking)

with open('1.txt') as f: 
    line = f.readline() 
    if "Logs" not in line: 
     print line 
    for line in f: 
     # f is an iterator so this will fetch the next line until EOF 
     print line 

파일이 비어 있으면 readline() 방법도 처리를 피하는 다소 더 "파이썬"

with open('1.txt') as f: 
    try: 
     line = next(f) 
     if "Logs" not in line: 
      print line 
    except StopIteration: 
     # if `f` is empty, `next()` will throw StopIteration 
     pass # you could also do something else to handle `f` is empty 

    for line in f: 
     # not executed if `f` is already EOF 
     print line