- 全缓冲
缓冲区满时才会嗲用时间的文件IO(除了终端设备的文件流,其他基本都是全缓冲) - 行缓冲
遇到换行符\n
才会调用文件IO.(终端设备就是行缓冲,如标准输入和标准输出,但是如果标准输入和输出重定向到某个文件时,就是全缓冲) - 无缓冲
直接调用文件IO(标准错误就是无缓冲)
Python IO实现raw层,Buffer层,Text层,直接操作Text层,open打开返回流对象,有一个buffer属性,既是Buffer层
ABC | Inherits | Stub Methods | Mixin Methods and Properties |
---|---|---|---|
IOBase | fileno, seek, and truncate | close, closed, enter, exit, flush, isatty, iter, next, readable, readline, readlines, seekable, tell, writable, and writelines | |
RawIOBase | IOBas | readinto and write | Inherited IOBase methods, read, and readall |
BufferedIOBase | IOBase | detach, read, read1, and write | Inherited IOBase methods, readinto, and readinto1 |
TextIOBase | IOBase | detach, read, readline, and write | Inherited IOBase methods, encoding, errors, and newlines |
class io.IOBase
方法 | 描述 |
---|---|
close() | 关闭流,closed 来判断是否关闭.此方法先调用flush |
fileno() | 文件描述符,整数 |
flush() | 刷新文件缓冲区 |
isatty() | 流是否与tty设备交互,返回True |
readable() | 可写,返回True |
readline(size=-1) | 读取一行 |
readlines(hint=-1) | 读取所有行,现在可以使用for line in file ,而不用调用file.readlines() |
seekable() | 如果为False seek(), tell(),truncate()都不可使用 |
truncate(size=None) | 重新设定流的大小 |
writable() | 可写返回True |
writelines(lines) | 多行写入 |
tell() | 当前位置 |
seek(offset, whence=SEEK_SET) | SEEK_SET文件开头0;SEEK_CUR1当前位置;文件结束SEEK_END2 |
class io.RawIOBase
方法 | 描述 |
---|---|
read(size=-1) | 读字节 |
readall() | 读所有字节 |
readinto(b) | 读字节写入到bytearray |
write(b) | readinto(b)的反向操作 |
class io.BufferedIOBase
方法 | 描述 |
---|---|
raw | 返回 RawIOBase |
detach() | 返回原始流 |
close() | 关闭流,closed 来判断是否关闭.此方法先调用flush |
fileno() | 文件描述符,整数 |
flush() | 刷新文件缓冲区 |
isatty() | 流是否与tty设备交互,返回True |
readable() | 可写,返回True |
readline(size=-1) | 读取一行 |
readlines(hint=-1) | 读取所有行,现在可以使用for line in file ,而不用调用file.readlines() |
seekable() | 如果为False seek(), tell(),truncate()都不可使用 |
truncate(size=None) | 重新设定流的大小 |
writable() | 可写返回True |
writelines(lines) | 多行写入 |
tell() | 当前位置,每次读取,位置都会后移 |
seek(offset, whence=SEEK_SET) | SEEK_SET文件开头0;SEEK_CUR1当前位置;文件结束SEEK_END2 |
Text I/O
方法 | 描述 |
---|---|
encoding | 编码 |
errors | |
newlines | 换行符 |
buffer | |
detach() | |
read(size=-1) | (str)读取所有 |
readline(size=-1) | (str)读取一行 |
readlines(hint=-1) | (list)读取所有行,现在可以使用for line in file ,而不用调用file.readlines() |
write(s) | |
seek(offset, whence=SEEK_SET) | |
tell() |
参考:
https://docs.python.org/3/library/functions.html#open