2012-01-28 4 views
1
#1 
input_file = 'my-textfile.txt' 
current_file = open(input_file) 
print current_file.readline() 
print current_file.readline() 

#2 
input_file = 'my-textfile.txt' 
print open(input_file).readline() 
print open(input_file).readline() 

# 1은 잘 작동하고 첫 번째와 두 번째 줄을 표시하지만 두 번째 줄은 두 번째 줄을 인쇄하고 # 1과 똑같이 인쇄하지 않는 이유는 무엇입니까?Python readline - 첫 번째 행만 읽습니다.

+4

정직한 질문이지만 진지하게 파이썬 프로그래밍 서적을 읽는 것이 좋습니다. 자신의 방식 오류를 완전히 이해하지 못한다면, 앞으로의 코드에서 이와 같은 실수는 매우 실망 스러울 것입니다. – EmmEff

+1

** ** 두 번 열어두면 **, 무엇을 기대 했습니까? 같은 줄을 두 번 얻습니다. –

답변

9

open으로 전화를 걸면 파일을 다시 열고 첫 번째 줄부터 시작합니다. 이미 열려있는 파일에서 readline을 호출 할 때마다 내부 "포인터"를 다음 줄의 시작 부분으로 이동합니다. 그러나 파일을 다시 열면 "포인터"도 다시 초기화됩니다. readline을 호출하면 첫 번째 줄을 다시 읽습니다.

class File(object): 
    """Instances of this class are returned by `open` (pretend)""" 

    def __init__(self, filesystem_handle): 
     """Called when the file object is initialized by `open`""" 

     print "Starting up a new file instance for {file} pointing at position 0.".format(...) 

     self.position = 0 
     self.handle = filesystem_handle 


    def readline(self): 
     """Read a line. Terribly naive. Do not use at home" 

     i = self.position 
     c = None 
     line = "" 
     while c != "\n": 
      c = self.handle.read_a_byte() 
      line += c 

     print "Read line from {p} to {end} ({i} + {p})".format(...) 

     self.position += i 
     return line 

당신이 당신의 첫 번째 예제를 실행했을 때 다음과 같은 출력 같은 것을 얻을 것이다 :

open이 닮은 file 객체를 반환 상상해

Starting up a new file instance for /my-textfile.txt pointing at position 0. 
Read line from 0 to 80 (80 + 0) 
Read line from 80 to 160 (80 + 80) 

동안의 출력 할 두 번째 예는 다음과 같습니다.

Starting up a new file instance for /my-textfile.txt pointing at position 0. 
Read line from 0 to 80 (80 + 0) 
Starting up a new file instance for /my-textfile.txt pointing at position 0. 
Read line from 0 to 80 (80 + 0) 
6

두 번째 코드 단편은 두 번 파일을 열 때마다 한 줄을 읽습니다. 파일이 새로 열리므로 매번 읽히는 첫 번째 줄입니다.

+0

고마워, 나는 지금 그것을 얻었다 :) – Tomas

관련 문제