2014-07-25 2 views
1

코드 :파일의 발생했음을 부분에서 공백을 제거

with open(filename) as f: 
    file_list = f.readlines() 
    file_list = [line.strip() for line in file_list] # remove whitespaces from each line of file 
    code to process data between start and end tags (these tags can have whitespaces thats why i have removed them above) 

이 코드는 나를을 위해 잘 작동하지만, 파일이 너무 큰 경우 다음 난에 전체 데이터를 복사하기 위해이 현명한 생각하지 않는다 목록에서 각 줄의 공백을 제거하십시오.

목록의 특정 부분에 대한 공백을 제거하여 목록에 저장할 수있는 부분을 많이 줄일 수 있습니까?

내가 시도 :

with open(filename) as f: 
    for line in f.readlines(): 
     if line.strip() == "start": 
      start = f.readlines.index("start") 
     if line.strip() == "end" 
      end = f.readlines.index("end") 
    file_list = f.readlines[start:end] 

을하지만 그것주는 오류

start = f.readlines.index("start") 
AttributeError: 'builtin_function_or_method' object has no attribute 'index' 

난 그냥이 게시물의 상단에 언급 한 코드의 효율적인 코드를 작성합니다.

+0

file : 읽을 줄이 더 이상 남아 있지 않습니다. 그러나 도움이 필요하면 사람들에게 문제가 무엇인지 알려주려고 노력해야합니다. – nekomatic

+0

'file_list = f.readlines(). strip()''이 코드는 잘 작동합니다. '- 정말요? 나는 지난번에 당신이 목록을 '스트립 (strip)'할 수 없다는 것을 확인한 이래로 이것이 오류라고 생각했을 것입니다 ... –

+0

@tobias_k 네, 맞습니다. 사실 나는 실수로 게시물을 작성했지만 지금은 게시물을 업데이트했습니다. – Patrick

답변

1

코드의 문제점은 파일 객체 f이 반복자는 것을, 그리고 당신이 f.readlines()를 호출하면 그렇게 f.readlines()다시이 작동하지 않을 수 호출하여 행의 인덱스를 찾는 소진되었습니다. 또한 readlines()을 모두으로 호출하면 파일의 흥미로운 부분 만 저장하지 않으므로 readlines()은 전체 파일을 메모리에 읽습니다.

대신 시작 줄을 이미 본 적이 있는지 기억하고 끝 줄이 나타날 때까지 다음 줄을 목록에 추가하십시오.

with open(filename) as f: 
    started, lines = False, [] 
    for line in f: 
     stripped = line.strip() 
     if stripped == "end": break 
     if started: lines.append(stripped) 
     if stripped == "start": started = True 

또는, 당신은 또한 최종 라인까지 모든 라인을 얻을 수 itertools.takewhile를 사용할 수 있습니다. 출발 선 앞에 선 읽기 (폐기) 다른 takewhile를 사용하여

import itertools 
with open(filename) as f: 
    for line in f: 
     if line.strip() == "start": 
      lines = itertools.takewhile(lambda l: l.strip() != "end", f) 
      lines = map(str.strip, lines) 
      break 

심지어 짧은 : 모든 경우에

with open("test.txt") as f: 
    list(itertools.takewhile(lambda l: l.strip() != "start", f)) 
    lines = itertools.takewhile(lambda l: l.strip() != "end", f) 
    lines = map(str.strip, lines) 

lines는 시작 - 사이 (제거) 라인을 보유하고 그리고 끝선, 둘 다 독점.

+0

위 게시판의 첫 번째 코드에서'if start :'if'started :'를 업데이트하십시오. – Patrick

+0

@Patrick Whops, 입력 위젯에서 코드를 개선하려고 할 때 발생하는 문제. –

0

토비아스의 첫 번째 대답은 ... continue로 조금 수정 될 수

with open(filename) as f: 
    started, lines = False, [] 
    for line in f: 
     stripped = line.strip() 
     if stripped == "end": break 
     if stripped == "start": 
      started = True 
      continue 
     if not started: continue 

     # process line here no need to store it in a list ... 
나는 첫 번째가의 끝에 파일 포인터를 둡니다 때문에 두 번째`의 readlines()가`실패 할 말할 수
관련 문제