2012-01-28 130 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工作正常並顯示第一行和第二行,但#2打印第一行的兩個副本,並且不打印與第一行相同的內容?Python readline - 只讀第一行

+4

一個誠實的問題,但我會認真地推薦閱讀一些入門的Python編程書籍。如果你沒有完全理解你的方式錯誤,在未來的代碼中這樣的錯誤將會非常令人沮喪。 – EmmEff 2012-01-28 19:29:08

+1

如果你**開了兩次**,你期望什麼?你會得到同一條線的兩倍。 – 2012-01-29 16:40:40

回答

9

當您致電open時,您將重新打開文件並從第一行開始。每當您在已打開的文件上撥打readline時,它會將其內部「指針」移動到下一行的開頭。但是,如果您重新打開文件,「指針」也會重新初始化 - 當您撥打readline時,它會再次讀取第一行。

試想一下,open返回file對象是這樣的:

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 

當你運行你的第一個例子中,你會得到類似以下的輸出:

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 2012-02-03 13:53:41