【问题标题】:What is the difference between read() and readline() in python? [duplicate]python中的read()和readline()有什么区别? [复制]
【发布时间】:2019-08-26 18:13:35
【问题描述】:

我现在正在学习 python 中的文件处理。如果我编写 read() 方法,它的工作原理与 readline() 方法相同。他们之间一定有区别,我想了解一下

【问题讨论】:

  • read() 将文件的所有内容读入字符串,readline 仅从文件中读取一行
  • 文档和您的研究中有哪些不清楚的地方?
  • 哦,我现在明白了。如果我在一行中使用“\n”,readline() 方法将停止读取

标签: python


【解决方案1】:

这个问题已经被回答了无数次,文档也很好地描述了这些差异。但这里是:

如果您有这样的文件 (test.txt):

first line
second line
third line

然后这段代码:

with open("test.txt", "r") as file:
    line = file.readline()
    print(line)

将产生这个输出:

first line

那是因为readline 只是读取下一行。

如果您改用此代码:

with open("test.txt", "r") as file:
    content = file.read()
    print(content)

输出:

first line
second line
third line

read() 将文件的全部内容读入一个字符串。 您还可以给read() 一个可选参数,它指定要从文件中读取的字符数:

with open("test.txt", "r") as file:
    content = file.read(15)
    print(content)

输出:

first line
seco

最后,你没有提到的第三个函数是readlines,它返回一个行列表(字符串):

with open("test.txt", "r") as file:
    lines = file.readlines()
    print(lines)

输出:

['first line\n', 'second line\n', 'third line\n']

【讨论】:

  • 这里还有很多其他的细微之处。就像对readline 的后续调用如何返回后续行,并且 both 以不同的速率消耗文件句柄。 OP 可能希望能够做到fh.read(); fh.read() 并且两者都相同,但它们不会
  • 谢谢@C.Nivs
【解决方案2】:

主要区别在于 read() 将一次读取整个文件,然后打印出占用括号中指定的字节数的第一个字符,而 readline() 将仅读取并打印出占用括号中指定的字节数的第一个字符。当您读取的文件对于您的 RAM 来说太大时,您可能需要使用 readline()。

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多