當您致電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)
一個誠實的問題,但我會認真地推薦閱讀一些入門的Python編程書籍。如果你沒有完全理解你的方式錯誤,在未來的代碼中這樣的錯誤將會非常令人沮喪。 – EmmEff 2012-01-28 19:29:08
如果你**開了兩次**,你期望什麼?你會得到同一條線的兩倍。 – 2012-01-29 16:40:40