python - python 内置的 open() 函数中的缓冲有什么用?

标签 python python-2.7

Python 文档:https://docs.python.org/2/library/functions.html#open

open(name[, mode[, buffering]])  

上述文档说“可选的缓冲参数指定文件所需的缓冲区大小:0 表示无缓冲,1 表示行缓冲,任何其他正值表示使用(大约)该大小(以字节为单位)的缓冲区。负缓冲表示使用系统默认值。如果省略,则使用系统默认值。"。
当我使用

filedata = open(file.txt,"r",0)  

filedata = open(file.txt,"r",1)  

filedata = open(file.txt,"r",2)

filedata = open(file.txt,"r",-1) 

filedata = open(file.txt,"r")

输出没有变化。上面显示的每一行都以相同的速度打印。
输出:

Mr. Bean is a British television programme series of fifteen 25-

minute episodes written by Robin Driscoll and starring Rowan Atkinson as

the title character. Different episodes were also written by Robin

Driscoll and Richard Curtis, and one by Ben Elton. Thirteen of the

episodes were broadcast on ITV, from the pilot on 1 January 1990, until

"Goodnight Mr. Bean" on 31 October 1995. A clip show, "The Best Bits of

Mr. Bean", was broadcast on 15 December 1995, and one episode, "Hair by

Mr. Bean of London", was not broadcast until 2006 on Nickelodeon.

那么open()函数中的缓冲参数有什么用呢?什么 值(value)

那个缓冲参数最好用?

最佳答案

启用缓冲意味着您不直接与操作系统的文件表示或其文件系统 API 进行交互。取而代之的是,从原始 OS 文件流中将一大块数据读取到缓冲区中,直到它被消耗,此时更多的数据被提取到缓冲区中。就您获得的对象而言,您将获得一个包装底层 RawIOBase (代表原始文件流)的 BufferedIOBase 对象。

这样做有什么好处?与原始流的良好接口(interface)可能具有很高的延迟,因为操作系统必须使用诸如硬盘之类的物理对象,这可能并非在所有情况下都可以接受。假设您想每 5 毫秒从一个文件中读取三个字母,而您的文件位于一个易碎的旧硬盘上,甚至是一个网络文件系统上。与其每 5ms 尝试从原始文件流中读取一次,不如将文件中的一堆字节加载到内存中的缓冲区中,然后随意使用它。

您选择的缓冲区大小取决于您使用数据的方式。对于上面的示例,1 个字符的缓冲区大小会很糟糕,3 个字符会很好,并且不会对您的用户造成明显延迟的 3 个字符的任何大倍数都是理想的。

关于python - python 内置的 open() 函数中的缓冲有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712445/

相关文章:

python - 是否可以将 Python Tornado 的 url 分解为多个文件?

python - 值错误 : too many values to unpack Scipy

python - 元组 bool 求值的意外行为

matlab - python中使用相关系数的两幅图像之间的百分比差异

python - wxpython 从 ID 访问对象

python - 如何确保从子文件夹中删除除 *.bin 文件之外的所有内容?

python - 数据框到json文件

python - ast.BoolOp 什么时候有两个以上的值?

Python 独有的 XML 规范化 (xml-exc-c14n)

python - 没有抛出错误,python 创建空白文件,不知道如何排除故障