Python 完美诠释高内聚概念的 IO 流 API 体系结构(全网最详细) (2)

只要在模式组合中有 'r' 关键字,则文件必须提前存在:

file = open("guo_ke.txt") file = open("guo_ke.txt", 'r') file = open("guo_ke.txt", 'rt') file = open("guo_ke.txt", 'r+t')

只要在模式组合中有 ‘w’ 关键字,则文件可以不必预先存在,如果存在,则原文件中内容会被清空。

# 可写 file = open("guo_ke.txt", 'w') # 可写、可读 file = open("guo_ke.txt", 'w+')

只要在模式组合中有 ‘a’ 关键字,则文件可以不必预先存在,如果存在,原文件中内空不会被清空

# 追加写 file = open("guo_ke.txt", 'a') # 追加写、且可读 file = open("guo_ke.txt", 'a+')

buffering: 设置缓冲策略。可取值为 0、1、>1 。

0: 在二进制模式下关闭缓冲。

1:在文本模式下使用行缓冲。

行缓冲:以行数据为单位进行缓存。

>1 的整数: 指定缓冲区的大小(以字节为单位)。

如果没有指定 buffering 参数,则会提供默认缓冲策略:

二进制文件使用固定大小的缓冲块。

在许多系统上,缓冲区的长度通常为 40968192 字节。

"Interactive" 文本文件( isatty() 返回 True 的文件)使用行缓冲。其他文本文件使用和二进制文件相同的缓冲策略。

isatty( ) 方法检测文件是否连接到一个终端设备。

encoding: 指定解码或编码文件时使用的编码名称。

只能用于文本文件。默认使用平台编码。

errors: 指定如何处理编码和解码时抛出的错误。可选项如下:

strict: 如果存在编码错误,则引发 ValueError 异常。 默认值 None 具有相同的效果。

ignore: 忽略错误。有可能会数据丢失。

replace: 会将替换标记(例如 '?' )插入有错误数据的地方。

newline: 在读或写文本内容时如何处理换行符号。可取值 None,' ','\n','\r' 和 '\r\n'。

OS 不同,换行符的描述也有差异。Unix 的行结束 '\n'、Windows 中为 '\r\n'

从流中读数据时,如果 newline 为 None,则启用平台约定换行模式。

写入流时,如果 newline 为 None,则写入的任何 '\n' 字符都将转换为系统默认行分隔符 。如果 newline 是 ' ' 或 '\n',则直接写入。如果 newline 是任何其他合法值,则写入的任何 '\n' 字符将被转换为给定的字符串。

closefd:

file = open("guo_ke.txt",closefd=False) ''' 输出结果 Traceback (most recent call last): File "D:/myc/filedmeo/文件嵌套.py", line 1, in <module> file = open("guo_ke.txt",closefd=False) ValueError: Cannot use closefd=False with file name '''

如果通过一个字符串路径描述打开文件, closefd 必须为 True (默认值),否则将引发错误。

file = open("guo_ke.txt", ) # 通过 file 文件的描述符打开文件 file1 = open(file.fileno(), closefd=False) file1.close() print("先打开文件:", file.closed) print("后打开文件:", file1.closed) ''' 输出结果 先打开文件: False 后打开文件: True '''

当 open file1 文件时设置为 closefd=False ,则当 file1 文件关闭后,file 文件将保持打开状态。

opener:可理解为 open( ) 函数是一个高级封装对象,本质是通过 opener 参数接入了一个真正的具有底层文件操作能力的接口。

import os def opener(path, flags): return os.open(path, flags) # 调用 opener('guo_ke.txt','r') 时的参数来自于 open() 的第一个和第二个 with open('guo_ke.txt', 'r', opener=opener) as f: print(f.read())

默认 opener 参数引用的就是 os.open( ) 方法。

3. 读写操作

调用 open( ) 函数后会返回一个 IO 流对象。IO 流对象中提供了常规的与读写相关的属性和方法。

class IO(Generic[AnyStr]): #返回文件的读写模式 @abstractproperty def mode(self) -> str: pass #返回文件的名称 @abstractproperty def name(self) -> str: pass #关闭文件 @abstractmethod def close(self) -> None: pass #判断文件是否关闭 @abstractproperty def closed(self) -> bool: pass #返回文件描述符号,每打开一个文件,python 会分配一个唯一的数字描述符号 @abstractmethod def fileno(self) -> int: pass #刷新缓存中的内容 @abstractmethod def flush(self) -> None: pass #是否连接到一个终端设备 @abstractmethod def isatty(self) -> bool: pass # 参数 n 为 -1 或不传递时,一次性读取文件中的所有内容,如果文件内容过多,可分多次读取 # 读取到文件末尾时,返回一个空字符串 ('') @abstractmethod def read(self, n: int = -1) -> AnyStr: pass # 文件是否可读 @abstractmethod def readable(self) -> bool: pass # 从文件中读取一行;换行符(\n)留在字符串的末尾 # 返回一个空的字符串时,表示已经到达了文件末尾 # 空行使用 '\n' 表示 @abstractmethod def readline(self, limit: int = -1) -> AnyStr: pass # 读取所有行并存储到列表中 # 也可以使用 list(f) @abstractmethod def readlines(self, hint: int = -1) -> List[AnyStr]: pass # 移动读写光标,改变文件的读写位置 # 通过向一个参考点添加 offset 来计算位置;参考点由 whence 参数指定。 # whence 的 0 值表示从文件开头起算,1 表示使用当前文件位置,2 表示使用文件末尾作为参考点。 # whence 如果省略则默认值为 0,即使用文件开头作为参考点。 @abstractmethod def seek(self, offset: int, whence: int = 0) -> int: pass # 是否可以移动光标 @abstractmethod def seekable(self) -> bool: pass # 返回文件的当前位置 @abstractmethod def tell(self) -> int: pass # 清除内容 @abstractmethod def truncate(self, size: int = None) -> int: pass # 是否可写 @abstractmethod def writable(self) -> bool: pass # 向文件写入内容 @abstractmethod def write(self, s: AnyStr) -> int: pass #向文件写入一行数据 @abstractmethod def writelines(self, lines: List[AnyStr]) -> None: pass

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzfysf.html