Python readline - 只读取第一行

时间:2012-01-28 19:16:27

标签: 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打印第一行的2份副本而不打印#1?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:6)

第二个代码段打开文件两次,每次读取一行。由于文件是重新打开的,因此每次都是第一行读取。