【问题标题】:Python readline - reads only first linePython readline - 只读取第一行
【发布时间】:2014-02-12 17:13:29
【问题描述】:
#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 相同的内容?

【问题讨论】:

  • 一个诚实的问题,但我强烈建议您阅读一些 Python 编程入门书籍。如果你不完全理解你的方式的错误,在以后的代码中出现这样的错误会非常令人沮丧。
  • 如果您打开两次,您期望什么?你得到两次相同的线。

标签: python readline


【解决方案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)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-01-15
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 2022-08-21
      相关资源
      最近更新 更多