문제

다른 프로그램에서 오류를 기록하고 오류가 발생할 때 중단 된 프로그램을 다시 시작하는 스크립트를 작성합니다. 어떤 이유로 든,이 프로그램의 개발자는이 기능을 기본적으로 프로그램에 넣을 필요가 없다고 생각했습니다.

어쨌든, 프로그램은 입력 파일을 가져 와서 구문 분석하고 출력 파일을 만듭니다. 입력 파일은 특정 형식입니다.

UI - 26474845
TI - the title (can be any number of lines)
AB - the abstract (can also be any number of lines)

프로그램에 오류가 발생하면 오류를 추적하는 데 필요한 참조 정보, 즉 UI (제목 또는 초록) 및 제목 또는 초록의 시작과 관련된 줄 번호를 제공합니다. 참조 번호와 파일을 가져오고 문장을 찾아서 로그인하는 함수로 입력 파일에서 불쾌한 문장을 기록하고 싶습니다. 내가 그렇게 생각할 수있는 가장 좋은 방법은 특정 횟수 (즉, n 시간, 여기서 n은 Seciton의 시작과 관련된 줄 번호)를 앞으로 나아가는 것과 관련이 있습니다. 이를 수행하는 것이 합리적 인 방식은 다음과 같습니다.

i = 1
while i <= lineNumber:
    print original.readline()
    i += 1

이것이 어떻게 데이터를 잃게 만드는지 모르겠지만 Python은 그럴 것이라고 생각하고 말합니다. ValueError: Mixing iteration and read methods would lose data. 누구 든지이 작업을 제대로 수행하는 방법을 아는 사람이 있습니까?

도움이 되었습니까?

해결책

You get the ValueError because your code probably has for line in original: in addition to original.readline(). An easy solution which fixes the problem without making your program slower or consume more memory is changing

for line in original:
    ...

to

while True:
    line = original.readline()
    if not line: break
    ...

다른 팁

Use for and enumerate.

Example:

for line_num, line in enumerate(file):
    if line_num < cut_off:
        print line

NOTE: This assumes you are already cleaning up your file handles, etc.

Also, the takewhile function could prove useful if you prefer a more functional flavor.

Assuming you need only one line, this could be of help

import itertools

def getline(fobj, line_no):
    "Return a (1-based) line from a file object"
    return itertools.islice(fobj, line_no-1, line_no).next() # 1-based!

>>> print getline(open("/etc/passwd", "r"), 4)
'adm:x:3:4:adm:/var/adm:/bin/false\n'

You might want to catch StopIteration errors (if the file has less lines).

Here's a version without the ugly while True pattern and without other modules:

for line in iter(original.readline, ''):
    if …:   # to the beginning of the title or abstract
        for i in range(lineNumber):
            print original.readline(),
        break
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top