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却打印了两遍第一行,并且没有像#1那样打印?
2 个回答
6
第二段代码打开文件两次,每次读取一行。因为每次打开文件都是从头开始,所以每次读取的都是第一行。
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)