
上QQ阅读APP看书,第一时间看更新
2.8 Python文件处理
在文件处理方面,Python使用open()方法打开一个文件,并返回文件对象。如果该文件无法被打开,会抛出OSError。使用open()方法时,一定要关闭文件对象,即调用close()方法。open()通常接收两个参数:file和mode。
open(file,mode='r')
完整的语法格式为:
open(file,mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
相关参数说明如下:
·file:必需,文件路径(相对或者绝对路径)。
·mode:可选,文件打开模式。
·buffering:设置缓冲。
·encoding:一般使用utf8。
·errors:报错级别。
·newline:区分换行符。
·closefd:传入的file参数类型。
·opener:设置自定义开启器,开启器的返回值必须是一个打开的文件描述符。
file对象使用open函数来创建,表2-14列出了file对象常用的函数。
表2-14 file对象常用的函数


mode(文件打开模式)有多种取值,相关描述如表2-15所示。
表2-15 mode的多种取值及其描述
