一、buffering 缓冲策略
Python中,open() 内建函数,是用来打开文件, 根据设定的参数来创造一个文件对象.
完整的格式:
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
其中 buffering
参数,用来指定访问文件所采用的缓冲方式。open()函数操作的文件主要有三类:可交互文本文件、普通文本文件、二进制文件,根据文件类型的不同,缓冲策略又有差别,具体如下:
buffering | 可交互文本文件 | 普通文本文件 | 二进制文件 |
---|---|---|---|
-1 |
表示行缓冲,即遇到换行符就flush | io.DEFAULT_BUFFER_SIZE |
io.DEFAULT_BUFFER_SIZE |
0 |
文本模式不支持 | 文本模式不支持 | 表示关闭buffer,即不缓冲 |
1 |
表示行缓冲,即遇到换行符就flush | 表示行缓冲,即遇到换行符就flush | io.DEFAULT_BUFFER_SIZE 网上有说buffering=1时,表示1字节缓冲区??? 从测试结果看是 io.DEFAULT_BUFFER_SIZE |
>1 |
io.DEFAULT_BUFFER_SIZE |
io.DEFAULT_BUFFER_SIZE |
使用buffering设置的值作为缓冲区大小,这个值可以>io.DEFAULT_BUFFER_SIZE |
- 怎么理解可交互式文本文件?就是连接到终端设备的文件,即
fileObject.isatty()
返回值为True
的文件。例如:控制台的标准输出流你就可以简单的理解为一个可交互文本文件; open()
函数声明中,buffering=None
,表示默认缺省,等效于buffering=-1
;- 在大多数系统中,
io.DEFAULT_BUFFER_SIZE
默认是4096
或8192
字节长度。可以通过下面的代码来获取这个值
import io
print(io.DEFAULT_BUFFER_SIZE)
引用
builtins.py
中open()
函数注释原文:
When no buffering argument is given, the default buffering policy works as follows:
- Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying device’s
“block size” and falling back onio.DEFAULT_BUFFER_SIZE
.
On many systems, the buffer will typically be 4096 or 8192 bytes long.- “Interactive” text files (files for which
isatty()
returns True)
use line buffering. Other text files use the policy described above
for binary files.
二、示例
下面举几个示例,帮助你理解可交互文本文件、普通文本文件的buffering如何控制缓存策略的。
1. 可交互文本文件
# -*- coding:utf-8 -*-
# test.py
import datetime,time
import sys
with open(sys.stdout.fileno()