蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

文件对象:open参数、缓冲、描述符与十三种方法

区分文本字符、二进制字节、缓冲和文件所有权,逐项观察真实文件结果。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先正确打开和关闭文件

open是内置函数,返回的对象类型取决于模式和缓冲配置。file既可为相对/绝对路径及PathLike,也可为已打开的整数文件描述符,不只是字符串文件名。无法打开常见OSError子类;参数错误还可能是ValueError或TypeError。

推荐with open(path, encoding="utf-8") as stream管理资源,正常或异常退出都会关闭已成功进入的流;手工打开时要在finally等适当位置关闭。关闭不等于所有属性都不可访问,也不能忽略读写过程可能抛出的错误。

逐个理解完整参数

完整入口为open(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)。mode决定读写/创建/更新及文本二进制;encoding只用于文本,默认受平台、地区及UTF-8模式影响,本站示例明确指定UTF-8。

buffering控制I/O缓冲而非文件权限:0只适合二进制无缓冲,1请求文本行缓冲,其它正值与默认策略另有规则;TextIOWrapper还有自己的编码与文本层。errors是编码解码错误处理策略,例如strict抛异常、ignore会丢信息、replace代换,不是日志报错级别。

newline控制文本行结束的识别和翻译。读取None时识别CR/LF/CRLF并统一为LF,空串保留识别到的原行尾;写入明确LF或CRLF时比较真实磁盘字节,不能把Windows行结束长度推广给所有文本配置。

closefd=False只适用于传入整数描述符,让流关闭后仍保留该描述符;传路径时不能用它来跳过流关闭。opener接收(file, flags)并返回打开的描述符,本章只允许打开本次临时目录中的文件,确认实际内容与资源所有权。

模式字符与历史迁移

t与b选择文本/二进制,+增加更新能力;r要求已有文件,w打开即截断或创建,a按追加语义写入,x要求路径不存在。rb/rb+/wb/wb+/ab/ab+等并非不同编码,字节与字符语义分开,r+b等合法拼写也逐个运行。

U属于历史通用换行标志,Python3.3起弃用、3.11移除,并非所有Python3版本一直不支持。当前3.12实际抛ValueError;现代文本模式使用newline参数保留通用换行知识。

关闭、刷新、描述符和终端

close使资源关闭,通常返回None,重复关闭可行,closed状态仍可检查;关闭后读写会失败。flush将Python层缓冲交给底层流,另开读取可看到新内容,但不能因此证明断电后数据已持久化。文件系统同步请求另用适当的os.fsync。

fileno给出底层整数描述符,可能用于os.fstat/read等接口;内存流等对象未必支持。isatty检查连接是否为终端,本章的普通临时文件为False,不把该结果泛化到终端窗口。

读取、迭代与定位

Python3没有file.next方法,迭代用next(stream)或for,耗尽抛StopIteration。read(size)在文本按字符、二进制按字节,0也可在未到EOF时返回空;负数/省略通常读取剩余内容。

readline可带长度上限,并可能只读到一行片段;完整行的行结束一般保留,空行与EOF分开。readlines返回行列表,hint是整行累计提示,不是精确字节切片;本章用多字节汉字实际展示。

seek/tell受流类型限制。二进制可按开始/当前/末尾计算字节偏移;文本tell更接近可恢复cookie,不能当任意字符索引。本站保存cookie后seek恢复,不把UTF-8位置等同已读字符数量。

截断与写入的准确单位

truncate(size)改变底层文件的字节长度,省略通常采用当前位置,不改变当前游标;可缩短,也可扩展,扩展填充受平台影响。本机Windows实际保留前缀并补零,不能说永远只可缩小或按字符截断。

文本write接收str并返回字符数;二进制流接收字节类并返回字节数。writelines接收字符串可迭代对象并返回None,不自动添加换行,不限必须传列表。本章最终比较磁盘字节,同时保留异常关闭的真实观察。

open八个参数

参数用途返回/行为条件
file路径/PathLike或整数FD打开或包装文件不是只能传文件名字符串
mode读取/写入/追加/独占及文本二进制决定对象能力基本r/w/a/x需合法组合
buffering缓冲策略0二进制无缓冲,1文本行缓冲默认策略和文本层不同
encoding文本编码str与字节间转换只用于文本;建议显式UTF-8
errors编解码错误处理strict/ignore/replace/surrogateescape等不是报错等级;丢弃会损信息
newline文本行结束识别/翻译None/空串/指定结束符读与写规则分开
closefd关闭流是否关闭传入FDFalse保留FD传路径时必须True
opener(file,flags)回调返回已打开FD本章限自有临时文件

完整模式及历史标志

标志/模式能力文件/位置条件补充边界
t文本标志与r/w/a/x等组合,例如rt返回文本流,不单指UTF-8
x独占新建路径已有则FileExistsError默认文本;xb字节;不自动创建父级
b二进制标志rb/wb等返回字节流不可同时指定文本encoding
+更新标志与基础模式组合,读写均可不改变r/w/a的存在与截断/追加前提
U历史通用换行3.3弃用,3.11移除当前ValueError,改用newline参数
r只读文本必须已有,不截断,开始位置默认基础模式
rb只读字节必须已有,不截断,开始位置图片等也可作为普通字节读取
r+读写文本必须已有,不截断,开始位置可覆盖局部内容
rb+读写字节必须已有,不截断,开始位置r+b等价合法拼写
w写文本创建或打开即清空,开始位置读操作不允许
wb写字节创建或打开即清空,开始位置读操作不允许
w+读写文本创建或打开即清空,开始位置读前需管理位置
wb+读写字节创建或打开即清空,开始位置w+b也合法
a追加文本不存在创建,初始末尾写入仍追加,即使调整读位置
ab追加字节不存在创建,初始末尾不是任何二进制编辑模式
a+追加读写文本不存在创建,初始末尾读取旧内容先seek
ab+追加读写字节不存在创建,初始末尾a+b也合法

十三个文件方法及迁移

入口参数返回/结果条件
close()无None;关闭底层资源closed可读,关闭后读写ValueError
flush()无None;刷新流缓冲不等于断电持久化证明
fileno()无整数文件描述符无底层FD的流可能不支持
isatty()无bool,是否终端连接普通文件False,终端另验
next(stream)可选默认值下一行;耗尽抛StopIteration或给定默认值Py3使用迭代协议,非file.next()
read(size=-1)最大字符/字节数量str或bytes文本字符;0不代表EOF
readline(size=-1)本次长度上限一行或片段,通常保留行尾空行与EOF不同
readlines(hint=-1)整行累计提示行列表不是严格字节截断,也不保证只读hint
seek(offset,whence=0)二进制字节偏移/文本cookie新的位置文本非零相对偏移受限
tell()无字节位置或文本cookie不可泛化为字符索引
truncate(size=None)底层字节长度;省略采用位置调整后的长度可缩短/扩展,不移动当前游标
write(value)文本str/二进制bytes类写入字符/字节数量不能混用;可能失败或短写
writelines(lines)文本/二进制对应可迭代对象None不自动添加换行,不要求必须为list

本章自编源码与运行范围

Python · 阅读源码
"""蓝色天空网 mbsky.com:在新建自有临时目录观察文件参数及全部13方法。"""
from pathlib import Path
import sys,os,io,tempfile
P=Path(__file__).resolve().parent;sys.path.insert(0,str(P))
from mbsky_pychecks import Checks
def main():
 c=Checks();root=P/"_runtime-work";root.mkdir(exist_ok=True)
 with tempfile.TemporaryDirectory(prefix="file-methods-",dir=root)as folder:
  work=Path(folder).resolve();assert work.is_relative_to(root.resolve())
  path=work/"天空.txt";path.write_bytes("蓝色天空网\nmbsky.com\n".encode())
  with open(path,encoding="utf8")as f:
   c.eq("open PathLike actual text",f.read(),"蓝色天空网\nmbsky.com\n")
   c.eq("open text object type",isinstance(f,io.TextIOBase),True)
  with open(str(path),encoding="utf8")as f:c.eq("open str path text",f.readline(),"蓝色天空网\n")
  c.raises("missing path specific error",FileNotFoundError,lambda:open(work/"absent"))
  for mode in ["r","rb","r+","rb+","w","wb","w+","wb+","a","ab","a+","ab+","rt","x","xt","xb","r+b","w+b","a+b"]:
   q=work/(mode.replace("+","plus")+".dat")
   q.write_bytes(b"abc")
   if mode.startswith("x"):q.unlink()
   kwargs={}if"b"in mode else dict(encoding="utf8",newline="\n")
   with open(q,mode,**kwargs)as f:
    readable=mode.startswith("r")or"+"in mode;writable=mode[0]in"wxa"or"+"in mode
    c.eq("mode can read "+mode,f.readable(),readable);c.eq("mode can write "+mode,f.writable(),writable)
    c.eq("mode actual type "+mode,isinstance(f,io.BufferedIOBase)if"b"in mode else isinstance(f,io.TextIOBase),True)
    if writable:c.eq("mode write "+mode,f.write(b"Z"if"b"in mode else"Z"),1)
   c.eq("mode final bytes "+mode,q.read_bytes(),b"abc"if mode in["r","rb","rt"]else b"abcZ"if mode.startswith("a")else b"Zbc"if mode.startswith("r")else b"Z")
  c.raises("exclusive existing fails",FileExistsError,lambda:open(path,"x"))
  c.raises("legacy U removed current version",ValueError,lambda:open(path,"U"))
  c.raises("text unbuffered rejected",ValueError,lambda:open(path,"r",buffering=0,encoding="utf8"))
  with open(path,"rb",buffering=0)as f:c.eq("binary unbuffered FileIO",type(f)is io.FileIO,True)
  with open(path,"a",buffering=1,encoding="utf8")as f:c.eq("text line buffering requested",f.line_buffering,True)
  bad=work/"bad.txt";bad.write_bytes(b"A\xffB")
  with open(bad,encoding="utf8",errors="strict")as f:c.raises("decode strict error",UnicodeDecodeError,f.read)
  for errors,expected in [("ignore","AB"),("replace","A\ufffdB"),("surrogateescape","A\udcffB")]:
   with open(bad,encoding="utf8",errors=errors)as f:c.eq("decode handler "+errors,f.read(),expected)
  mixed=work/"mixed.txt";mixed.write_bytes(b"a\r\nb\rc\n")
  for newline,expected in [(None,"a\nb\nc\n"),("","a\r\nb\rc\n"),("\n","a\r\nb\rc\n")]:
   with open(mixed,encoding="utf8",newline=newline)as f:c.eq("newline read "+repr(newline),f.read(),expected)
  for newline,expected in [("\n",b"a\nb\n"),("\r\n",b"a\r\nb\r\n")]:
   q=work/("lf"if newline=="\n"else"crlf")
   with open(q,"w",encoding="utf8",newline=newline)as f:f.write("a\nb\n")
   c.eq("newline physical output "+repr(newline),q.read_bytes(),expected)
  fd=os.open(path,os.O_RDONLY|os.O_BINARY)
  with open(fd,"rb",closefd=False)as f:c.eq("fd wrap actual read",f.read(3),"蓝".encode())
  c.eq("closefd false fd alive",os.fstat(fd).st_size,path.stat().st_size);os.close(fd)
  fd=os.open(path,os.O_RDONLY|os.O_BINARY)
  with open(fd,"rb")as f:c.eq("fd wrap default owns fd",f.closefd if hasattr(f,"closefd")else f.raw.closefd,True)
  c.raises("closefd true descriptor closed",OSError,lambda:os.fstat(fd))
  c.raises("path cannot use closefd false",ValueError,lambda:open(path,closefd=False))
  opener_calls=[]
  def owned_opener(file,flags):
   target=Path(file).resolve();assert target.is_relative_to(work)
   opener_calls.append((target.name,isinstance(flags,int)));return os.open(target,flags,0o600)
  q=work/"custom.txt"
  with open(q,"w",encoding="utf8",opener=owned_opener)as f:f.write("mbsky.com")
  c.eq("custom opener actual arguments",opener_calls,[("custom.txt",True)])
  c.eq("custom opener file contents",q.read_bytes(),b"mbsky.com")
  f=open(path,encoding="utf8");c.eq("close return None",f.close(),None);c.eq("close actual flag",f.closed,True);c.eq("close repeat allowed",f.close(),None)
  c.raises("closed read raises",ValueError,f.read)
  q=work/"buffer.bin"
  with open(q,"w+b")as f:
   c.eq("write bytes returns byte count",f.write(b"ABC"),3)
   c.eq("flush returns None",f.flush(),None)
   c.eq("flush visible to separate reader",q.read_bytes(),b"ABC")
   c.eq("fileno integer",type(f.fileno())is int,True)
   c.eq("fileno actual fstat",os.fstat(f.fileno()).st_size,3)
   c.eq("isatty regular file",f.isatty(),False)
   c.eq("seek absolute",f.seek(1),1);c.eq("tell binary byte offset",f.tell(),1);c.eq("read size bytes",f.read(1),b"B")
  text=work/"lines.txt";text.write_bytes("天空\n\nabc".encode())
  with open(text,encoding="utf8")as f:
   c.eq("no next method",hasattr(f,"next"),False)
   c.eq("next builtin actual line",next(f),"天空\n")
   c.eq("next blank line not EOF",next(f),"\n")
   c.eq("next last line",next(f),"abc");c.raises("next EOF StopIteration",StopIteration,lambda:next(f))
  with open(text,encoding="utf8")as f:
   c.eq("read text size characters",f.read(1),"天");cookie=f.tell();c.eq("text cookie not character index",cookie!=1,True)
   c.eq("read remaining Unicode",f.read(),"空\n\nabc");f.seek(cookie);c.eq("text saved cookie restore",f.read(1),"空")
   c.eq("read0 even before EOF",f.read(0),"")
  with open(text,encoding="utf8")as f:
   c.eq("readline limited char size",f.readline(1),"天")
   c.eq("readline remaining includes newline",f.readline(),"空\n")
   c.eq("readline blank distinct",f.readline(),"\n");c.eq("readline final no newline",f.readline(),"abc");c.eq("readline EOF",f.readline(),"")
  with open(text,encoding="utf8")as f:c.eq("readlines hint whole Unicode line",f.readlines(1),["天空\n"])
  with open(text,encoding="utf8")as f:c.eq("readlines complete list",f.readlines(),["天空\n","\n","abc"])
  q=work/"truncate.bin";q.write_bytes(b"abcdef")
  with open(q,"r+b")as f:
   f.seek(2);c.eq("truncate omitted return size",f.truncate(),2);c.eq("truncate keeps cursor",f.tell(),2)
   c.eq("truncate shrinks bytes",q.read_bytes(),b"ab")
   c.eq("truncate grows beyond old size",f.truncate(5),5);c.eq("truncate growth actual zeros",q.read_bytes(),b"ab\0\0\0")
  q=work/"writes.txt"
  with open(q,"w",encoding="utf8",newline="\n")as f:
   c.eq("text write character count",f.write("天空"),2)
   c.eq("writelines no return",f.writelines(iter(["A","B\n","C"])),None)
  c.eq("writelines no automatic LF",q.read_bytes(),"天空AB\nC".encode())
  q=work/"exception.txt";held=None
  try:
   with open(q,"w",encoding="utf8")as held:held.write("本站");raise RuntimeError("owned expected")
  except RuntimeError:pass
  c.eq("with closes on exception",held.closed,True);c.eq("exception path saved bytes",q.read_bytes(),"本站".encode())
 c.eq("own temp removed",work.exists(),False)
 sys.stdout.reconfigure(errors="backslashreplace")
 c.finish("python3-file-methods",host=os.name,errors_are_codec_policies=True,source_code_executed=False,flush_not_power_loss_proof=True)
if __name__=="__main__":main()
运行本章核心实例

所需环境:本地 Python 环境

当前源码 SHA256:3c5e447d47b32240bbcb9ab1aab107780b0a481888e63a0850ad3f118d1fa5cd

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据