Python readline - 只读取第一行 [英] Python readline - reads only first line

查看:157
本文介绍了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 不同?

Why is it that #1 works fine and displays the first and second line, but #2 prints 2 copies of the first line and doesn't print the same as #1 ?

推荐答案

当您调用 open 时,您将重新打开文件并从第一行开始.每次在已经打开的文件上调用 readline 时,它都会将其内部指针"移动到下一行的开头.但是,如果您重新打开文件,指针"也会重新初始化 - 当您调用 readline 时,它会再次读取第一行.

When you call open you are opening the file anew and starting from the first line. Every time you call readline on an already open file it moves its internal "pointer" to the start of the next line. However, if you re-open the file the "pointer" is also re-initialized - and when you call readline it reads the first line again.

想象一下 open 返回一个 file 对象,看起来像这样:

Imagine that open returned a file object that looked like this:

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

当您运行第一个示例时,您会得到如下输出:

When you ran your first example you would get something like the following output:

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)

虽然你的第二个例子的输出看起来像这样:

While the output of your second example would look something like this:

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 readline - 只读取第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆