Python readline - 只读第一行

问题描述:

#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

当您致电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) 

第二个片段打开文件两次,每次读一行。由于该文件是重新打开的,每次它是第一行被读取。

+0

谢谢,我现在明白了:) – Tomas 2012-02-03 13:53:41