代码之家  ›  专栏  ›  技术社区  ›  Aviv Cohn

file.read()是否保证读取整个文件?

  •  2
  • Aviv Cohn  · 技术社区  · 7 年前

    file.read() 说:

        Notice that when in non-blocking mode, less data than what was requested
        may be returned, even if no size parameter was given.
    

    这是不是意味着 file.read() 放心 总是返回文本文件的全部内容,即使它很可能会返回? 如果是这样的话,读一个完整的文本文件的正确方法是什么?

    2 回复  |  直到 7 年前
        1
  •  1
  •   user2357112    7 年前

    对于不是常规文件的“文件”,如果您有 特别开启 其中的模式 file.read() file.read() 可能不会什么都读。

    file descriptor 在Unix中,这只对表示套接字、管道或其他通信设备的“文件”有效。在非阻塞模式下,如果您尝试读取比当前可用数据更多的数据,则该文件将提供它所拥有的数据,而不是等待足够的数据到达。

        2
  •  1
  •   Ho John Lee    7 年前

    如果是纯文本文件,您可以执行以下操作:

    with open("file.txt", "r") as infile:
        for line in infile:
             # something with a line of text here
             print(line)