#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 不同?
请您参考如下方法:
当您调用 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)
