打开模式
'r' open for reading (default)
以只读方式打开文件(默认)
'w' open for writing, truncating the file first
以写入的方式打开文件,会覆盖已存在的文件
'x' create a new file and open it for writing
如果文件已经存在,使用此模式打开将引发异常
'a' open for writing, appending to the end of the file if it exists
以写入模式打开,如果文件存在,则在末尾追加写入
'b' binary mode
以二进制模式打开文件
't' text mode (default)
以文本模式打开(打开text文本的默认方式)
'+' open a disk file for updating (reading and writing)
可读写模式(可添加到其他模式中使用)
'U' universal newline mode (deprecated)
通用换行符支持
read()、readline()和readlines()的区别
首先这三个读取方法都是IO类下的抽象方法,其源码如下:
@abstractmethod
def read(self, n: int = -1) -> AnyStr:
pass
@abstractmethod
def readline(self, limit: int = -1) -> AnyStr:
pass
@abstractmethod
def readlines(self, hint: int = -1) -> List[AnyStr]:
pass
read()方法传入int类型,表示读取文件字符长度,默认-1为全部;
- 优点:一次性读取全部内容
- 缺点:大文件会消耗大量服务器内存,读取出的字符串无法按行解析
readline()传入int值,该int值表示读取该行内的字符长度;
- 优点:每次只读一行内容,内存消耗较少
- 缺点:速度慢
readlines() 传入int值, 该int值表示读取该文件字符长度,和read()读取的长度一致,返回list类型,每行以换行符\n结束;
- 优点:一次性读取文件内全部内容,以list形式返回,利于按行解析文本
- 缺点:同时也会消耗大量内存