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

输入输出:格式、文件模式、位置与序列化

把字符、字节、文件游标和实际输出分别核对。

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

学完这一章,你能够

str、repr和表达式显示

print明确输出,表达式自动显示主要属于交互式显示钩子的行为,普通脚本中的裸表达式通常没有输出。str面向展示,repr面向诊断表达,并不保证任何对象的repr都可安全地eval还原。

本站保留浮点1/7、32.5与40000、嵌套值和换行转义的目标;显示文字统一为蓝色天空网与mbsky.com,不依靠固定对象地址作为结果。

格式化与对齐

两种平方/立方表分别使用repr加rjust,以及format宽度;逐行比较空格、宽度和末尾换行。ljust、center及带符号zfill产生新字符串,不写文件,宽度小于原长度也不会自动截断。

保留位置字段重排、关键字、位置与命名混合、!s/!r/!a、三位小数、整数宽度、字典索引字段及**展开。补充f-string的主流写法,同时保留%格式化知识;不能断言%已经确定会从语言移除。

标准输入与写入返回值

input从当前标准输入读取文本,标准输入可来自重定向而非物理键盘;正常行、空行和EOF分别处理。本章实际给子进程传入自有文本,不声称已经操作真实键盘。

文本write接收str并返回字符数量,二进制write接收字节对象并返回字节数量;写入不等于控制台显示。数字或元组先明确转换;直接把bytes写文本或把str写二进制会TypeError。

十二模式及完整对照矩阵

保留r/rb/r+/rb+、w/wb/w+/wb+、a/ab/a+/ab+的读、写、存在条件、创建、打开即截断及起始位置。模式中的+增加更新能力,b区分二进制;补充x独占创建和显式UTF-8。

流程图先分读取、写入和读写,再分截断/追加与初始位置;图中覆盖应理解为打开时清空。r+不会自动截断,但仍可从指定位置改写字节;a模式即使seek到开始,写入仍按追加语义到末尾。

模式测试只在本项目新建临时目录,分别用已有文件和不存在路径验证,不能为了演示w而覆盖用户文件。六列矩阵的每个单元格与实际读写/创建/截断/位置观察对应。末尾列表示追加模式的定位策略,不把空文件位置0同时位于首尾当成模式分类。

逐段、逐行和关闭

read(size)在文本流按字符、二进制流按字节;size为整数,0返回空结果不意味着已到EOF。readline保留读到的行结束,空行与EOF不同;readlines(hint)按整行收集并参考累计大小,不是精确读取hint字节。

普通读取与迭代共享位置,可顺序配合;CPython文本迭代优化可能暂时禁用tell,不能简单说两种方法一律不可混用。实际结果及具体对象类型分别记录。

close后read/write会失败,但closed属性仍可读,重复close通常可行;with能在正常和异常路径退出关闭文件。truncate才是准确方法名,不能将拼写错误trucate当接口。

二进制偏移与文本cookie

二进制seek的0/1/2分别从开始、当前位置、末尾按字节偏移。本章写入0123456789abcdef,先seek(5)读到5,再从末尾-3读到d,当前位置偏移也有独立检查。

文本tell通常返回可供恢复的cookie,不应当作通用字符索引或任意字节偏移。用保存的tell值配合seek恢复;文本流对相对当前/末尾的非零偏移有限制,而seek(0,1)与seek(0,2)等情形并非全部禁止。

可信自建pickle往返

pickle以二进制协议保存和恢复Python对象图,可以保留共享与自引用关系,不是读取一段普通文本再任意eval。本章只加载本站刚生成且校验过的自有数据;不反序列化外部下载的未知pickle。

明确分别使用默认、协议0和最高协议,不用注释声称未指定protocol的调用就是0。在一个自有文件依次保存字典与循环列表,再依次读回,核对类型、复数、共享/自引用及文件关闭;跨版本仍需兼容协议和对象定义。

十二种文件模式

模式读/写存在/创建/截断初始位置
r读必须存在,不截断开始
rb读bytes必须存在,不截断开始
r+读写文本必须存在,不截断开始
rb+读写bytes必须存在,不截断开始
w写文本不存在创建,存在截断开始
wb写bytes不存在创建,存在截断开始
w+读写文本不存在创建,存在截断开始
wb+读写bytes不存在创建,存在截断开始
a写文本不存在创建,不截断末尾
ab写bytes不存在创建,不截断末尾
a+读写文本不存在创建,不截断末尾
ab+读写bytes不存在创建,不截断末尾

六列模式矩阵

条件rr+ww+aa+
读是是否是否是
写否是是是是是
创建否否是是是是
打开即截断否否是是否否
按打开策略从开始是是是是否否
按追加语义在末尾否否否否是是

流方法与返回值

入口参数/结果限制
read(size=-1)文本字符或bytes0可在未EOF时返回空;size须整数
readline(size=-1)一行或片段空行与EOF不同
readlines(hint=-1)完整行列表hint非精确字节上限
write(value)字符或字节数量取决于文本/二进制对象
tell()位置或文本cookie不可一概当字符索引
seek(offset,whence=0)恢复位置文本与二进制规则不同
close()关闭资源closed仍可读,重复关闭通常可行
truncate(size)改变文件长度不是trucate
isatty()是否终端常规文件False
pickle.dump/load自有二进制对象图仅可信数据;协议须明确

本章自编源码与运行范围

Python · 阅读源码
"""蓝色天空网 mbsky.com — 格式化、临时文件和可信自建pickle。"""
from pathlib import Path
import sys,io,contextlib,tempfile,subprocess,math,pickle,pickletools,pprint
P=Path(__file__).resolve().parent;sys.path.insert(0,str(P))
from mbsky_pychecks import Checks
def input_mode():
    try:value=input("请输入:")
    except EOFError:print("EOF");return
    print("记录:",value)
def main():
    if len(sys.argv)>1 and sys.argv[1]=="--read-input":input_mode();return
    c=Checks()
    c.eq("str display","蓝色天空网",str("蓝色天空网"))
    c.eq("repr quote escaped newline",repr("sky\n"),"'sky\\n'")
    c.eq("float1 seventh",str(1/7),"0.14285714285714285")
    c.eq("repr nested values",repr((32.5,40000,("HTML","CSS"))),"(32.5, 40000, ('HTML', 'CSS'))")
    bare=subprocess.run([sys.executable,"-I","-B","-X","utf8","-c","3+4"],capture_output=True,text=True,encoding="utf8",timeout=5)
    c.eq("bare expression script no output",bare.stdout,"")
    repl=subprocess.run([sys.executable,"-I","-B","-X","utf8","-i","-c","pass"],input="3+4\nexit()\n",capture_output=True,text=True,encoding="utf8",timeout=5)
    c.eq("real interactive expression display",repl.stdout,"7\n")
    left=io.StringIO();right=io.StringIO()
    with contextlib.redirect_stdout(left):
        for x in range(1,11):
            print(repr(x).rjust(2),repr(x*x).rjust(3),end=" ");print(repr(x*x*x).rjust(4))
    with contextlib.redirect_stdout(right):
        for x in range(1,11):print("{0:2d} {1:3d} {2:4d}".format(x,x*x,x*x*x))
    c.eq("two table formatting methods exact",left.getvalue(),right.getvalue())
    c.eq("table first row spaces",left.getvalue().splitlines()[0]," 1   1    1")
    c.eq("table final row",left.getvalue().splitlines()[-1],"10 100 1000")
    c.eq("table ten rows",len(left.getvalue().splitlines()),10)
    c.eq("left align","sky".ljust(5),"sky  ");c.eq("center align","sky".center(5)," sky ")
    c.eq("zfill plain","12".zfill(5),"00012");c.eq("zfill sign","-3.14".zfill(7),"-003.14")
    c.eq("small width no truncation","3.14159265359".zfill(5),"3.14159265359")
    c.eq("brand basic format",'{}网址:"{}!"'.format("蓝色天空网","mbsky.com"),'蓝色天空网网址:"mbsky.com!"')
    c.eq("format positional swap","{1} 和 {0}".format("HTML","CSS"),"CSS 和 HTML")
    c.eq("format named","{name} {site}".format(name="蓝色天空网",site="mbsky.com"),"蓝色天空网 mbsky.com")
    c.eq("format mixed named positional","{0},{1},{other}".format("HTML","CSS",other="Python"),"HTML,CSS,Python")
    c.eq("format three conversions","{0!s}|{0!r}|{0!a}".format("天"),"天|'天'|'\\u5929'")
    c.eq("PI3 decimal format","{0:.3f}".format(math.pi),"3.142")
    c.eq("legacy percent3 decimal","%5.3f"%math.pi,"3.142")
    c.eq("fstring main style",f"{math.pi:.3f}","3.142")
    table={"HTML":1,"CSS":2,"Python":3}
    c.eq("format minimum widths","{0:10} ==> {1:10d}".format("HTML",1),"HTML       ==>          1")
    c.eq("format mapping index","CSS:{0[CSS]:d};HTML:{0[HTML]:d}".format(table),"CSS:2;HTML:1")
    c.eq("format mapping expansion","CSS:{CSS:d};HTML:{HTML:d}".format(**table),"CSS:2;HTML:1")
    c.raises("format missing key",KeyError,lambda:"{missing}".format(**table))
    c.raises("format auto/manual conflict",ValueError,lambda:"{} {0}".format(1))
    c.raises("format wrong spec type",ValueError,lambda:"{:d}".format("1"))
    input_runs=[]
    for label,data,expected in[("text","蓝色天空网\n","请输入:记录: 蓝色天空网\n"),("blank","\n","请输入:记录: \n"),("EOF","","请输入:EOF\n")]:
        r=subprocess.run([sys.executable,"-I","-B","-X","utf8",__file__,"--read-input"],input=data,capture_output=True,text=True,encoding="utf8",timeout=5)
        c.eq("stdin exit "+label,r.returncode,0);c.eq("stdin output "+label,r.stdout,expected)
        input_runs.append(dict(label=label,stdin=data,stdout=r.stdout,stderr=r.stderr))
    work=P/"_runtime-work";work.mkdir(exist_ok=True);mode_contracts=[]
    with tempfile.TemporaryDirectory(prefix="io-",dir=work)as folder:
        root=Path(folder);assert root.resolve().is_relative_to(work.resolve())
        for mode in["r","rb","r+","rb+","w","wb","w+","wb+","a","ab","a+","ab+"]:
            path=root/("mode-"+mode.replace("+","plus")+".dat");path.write_bytes(b"abc")
            binary="b"in mode;kwargs={}if binary else{"encoding":"utf8","newline":"\n"}
            readable=mode.startswith("r")or"+"in mode;writable=mode[0]in"wa"or"+"in mode
            with path.open(mode,**kwargs)as f:
                position=f.tell();truncated=path.stat().st_size==0
                c.eq("mode readable "+mode,f.readable(),readable);c.eq("mode writable "+mode,f.writable(),writable)
                c.eq("mode initial position "+mode,position,3 if mode.startswith("a")else 0)
                c.eq("mode truncate "+mode,truncated,mode.startswith("w"))
                if readable:
                    f.seek(0);expected=(b""if mode.startswith("w")else b"abc")
                    c.eq("mode actual read "+mode,f.read(),expected if binary else expected.decode())
                else:c.raises("mode cannot read "+mode,io.UnsupportedOperation,lambda:f.read())
                if writable:
                    f.seek(0);c.eq("mode write length "+mode,f.write(b"Z"if binary else"Z"),1);f.flush()
                else:c.raises("mode cannot write "+mode,io.UnsupportedOperation,lambda:f.write(b"Z"if binary else"Z"))
            expected=b"abcZ"if mode.startswith("a")else b"Z"if mode.startswith("w")else b"Zbc"if writable else b"abc"
            c.eq("mode final bytes "+mode,path.read_bytes(),expected)
            missing=root/("new-"+mode.replace("+","plus")+".dat")
            if mode.startswith("r"):
                c.raises("mode missing fails "+mode,FileNotFoundError,lambda:missing.open(mode,**kwargs));created=False
            else:
                with missing.open(mode,**kwargs):pass
                created=missing.exists();c.eq("mode creates missing "+mode,created,True)
            mode_contracts.append(dict(mode=mode,readable=readable,writable=writable,creates=created,truncates=truncated,initial=position,final_bytes_hex=path.read_bytes().hex()))
        exclusive=root/"exclusive.txt"
        with exclusive.open("x",encoding="utf8")as f:f.write("owned")
        c.raises("exclusive refuses overwrite",FileExistsError,lambda:exclusive.open("x",encoding="utf8"))
        textfile=root/"text.txt"
        with textfile.open("w",encoding="utf8",newline="\n")as f:
            c.eq("text write counts characters",f.write("天\n"),2)
            c.raises("text rejects bytes",TypeError,lambda:f.write(b"x"))
        c.eq("UTF8 physical byte length",len(textfile.read_bytes()),4)
        binaryfile=root/"binary.dat"
        with binaryfile.open("wb")as f:
            c.eq("binary write counts bytes",f.write("天\n".encode()),4)
            c.raises("binary rejects str",TypeError,lambda:f.write("x"))
        c.eq("text/binary explicit same encoded bytes",textfile.read_bytes(),binaryfile.read_bytes())
        textfile.write_text("aa\n\nbbb",encoding="utf8",newline="\n")
        with textfile.open(encoding="utf8")as f:
            c.eq("read0 before EOF",f.read(0),"");c.eq("read1 character",f.read(1),"a")
            c.eq("readnegative remaining",f.read(-1),"a\n\nbbb");c.eq("read EOF",f.read(),"")
        with textfile.open(encoding="utf8")as f:
            c.eq("readline first includes LF",f.readline(),"aa\n")
            c.eq("blank line not EOF",f.readline(),"\n")
            c.eq("last line without LF",f.readline(),"bbb");c.eq("readline EOF only now",f.readline(),"")
        with textfile.open(encoding="utf8")as f:c.eq("readlines whole lines",f.readlines(),["aa\n","\n","bbb"])
        with textfile.open(encoding="utf8")as f:c.eq("readlines hint not exact bytes",f.readlines(1),["aa\n"])
        with textfile.open(encoding="utf8")as f:
            c.eq("iteration first line",next(f),"aa\n");c.eq("manual read after iteration",f.read(),"\nbbb")
        with textfile.open(encoding="utf8")as f:
            next(f);c.raises("text iterator may disable tell",OSError,f.tell)
        with textfile.open(encoding="utf8")as f:c.raises("read size not float",TypeError,lambda:f.read(1.5))
        textfile.write_text("天\n空\n",encoding="utf8",newline="\n")
        with textfile.open(encoding="utf8")as f:c.eq("unicode hint counts whole character lines",f.readlines(2),["天\n","空\n"])
        binaryfile.write_bytes(b"0123456789abcdef")
        with binaryfile.open("rb+")as f:
            c.eq("binary seek absolute5",f.seek(5),5);c.eq("binary byte5",f.read(1),b"5")
            c.eq("binary seek endminus3",f.seek(-3,2),13);c.eq("binary byte d",f.read(1),b"d")
            c.eq("binary seek relative back1",f.seek(-1,1),13);c.eq("binary d repeated",f.read(1),b"d")
            c.eq("file is not terminal",f.isatty(),False)
            c.eq("truncate return size",f.truncate(3),3)
        c.eq("truncate actual bytes",binaryfile.read_bytes(),b"012")
        textfile.write_bytes("天空\n".encode())
        with textfile.open(encoding="utf8")as f:
            c.eq("unicode read one char",f.read(1),"天");cookie=f.tell()
            c.eq("tell is not character count",cookie!=1,True)
            rest=f.read();f.seek(cookie);c.eq("saved text cookie restores",f.read(),rest)
            c.raises("text nonzero current offset unsupported",io.UnsupportedOperation,lambda:f.seek(1,1))
            c.raises("text nonzero end offset unsupported",io.UnsupportedOperation,lambda:f.seek(-1,2))
            c.eq("text seek0 current supported",type(f.seek(0,1)).__name__,"int")
            c.eq("text seek0 end supported",type(f.seek(0,2)).__name__,"int")
        c.eq("with closed actually",f.closed,True);c.eq("close again is allowed",f.close(),None)
        c.raises("closed read fails",ValueError,f.read)
        obj={"a":[1,2.0,3,4+6j],"b":("string","中文"),"c":None}
        cycle=[1,2,3];cycle.append(cycle);dumpfile=root/"owned.pkl"
        c.eq("fixed Python3.12 default protocol",pickle.DEFAULT_PROTOCOL,4)
        c.eq("fixed Python3.12 highest protocol",pickle.HIGHEST_PROTOCOL,5)
        with dumpfile.open("wb")as f:
            pickle.dump(obj,f);pickle.dump(cycle,f,protocol=pickle.HIGHEST_PROTOCOL)
        with dumpfile.open("rb")as f:
            restored=pickle.load(f);recursion=pickle.load(f);c.raises("pickle after two objects EOF",EOFError,lambda:pickle.load(f))
        c.eq("pickle dictionary actual roundtrip",restored,obj)
        c.eq("pickle cycle prefix",recursion[:3],[1,2,3]);c.eq("pickle self identity preserved",recursion[-1]is recursion,True)
        c.eq("pprint cycle readable","Recursion on list"in pprint.pformat(recursion),True)
        explicit0=pickle.dumps(obj,protocol=0)
        c.eq("explicit protocol0 first opcode",next(pickletools.genops(explicit0))[0].name,"MARK")
        c.eq("explicit protocol0 roundtrip",pickle.loads(explicit0),obj)
        current=pickle.dumps(obj);c.eq("default pickle header protocol",next(pickletools.genops(current))[1],4)
        c.raises("malformed own pickle rejected",pickle.UnpicklingError,lambda:pickle.loads(b"not pickle"))
    c.eq("owned temporary directory cleaned",Path(folder).exists(),False)
    c.finish("python3-inputoutput",mode_contracts=mode_contracts,stdin_runs=input_runs,text_cookie_observed=cookie,untrusted_or_source_pickle_loaded=False)
if __name__=="__main__":main()
运行本章核心实例

所需环境:本地 Python 环境

当前源码 SHA256:bac6f953a83ceac73cc2ef61d20fef71e7106e04fe5c8f90c306136162e6b8a9

下载本站示例源码

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

常见错误与边界

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

练习与解答

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

展开参考解答

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

规范与官方依据