蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHON本地 Python 环境python3-file-methods.py
python3-file-methods.py104 行
"""蓝色天空网 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 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python3-file-methods.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python3-file-methods.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习