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

文件对象的方法与描述符

对照文本流、二进制流与底层描述符的参数、返回值和失败边界。

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

学完这一章,你能够

打开流时先决定数据类型

open 得到文件对象。文本模式处理 str,二进制处理 bytes。显式选择编码和错误策略可避免把本机默认设置当成文件格式。打开可能因为路径、权限或文件状态失败,用 with 管理成功打开后的生命周期。

先按 r、w、x、a 选择基本动作,再加 t、b 或 +。历史 U 由现代 newline 参数替代。下表中的追加初始位置来自本机普通文件观察,追加写入行为和当前读位置要分开理解。

迭代、查找位置与长度

read 和 readline 的单位取决于流类型。读取到行尾时,行终止符通常属于返回内容。readlines 的 hint 不能当成逐次只读固定字节数,迭代通常更适合逐行处理大文件。

二进制定位可用开始、当前和末尾三种参照。文本 tell 的结果可当作可恢复状态的标记。truncate 修改长度而不移动当前位置,下面用独立二进制文件验证。

缓冲和描述符的所有权

flush 把 Python 缓冲送向底层,磁盘持久化另有系统条件。fileno 返回描述符,但内存流可能没有。closefd 只决定包装整数描述符时关闭流是否也关闭描述符。

历史 file.next() 迁移到 next(stream)。write 与 writelines 不会自行插入换行。文件、管道和真实终端是不同设备,示例先在可控的普通文件上验证 isatty。

打开模式及读写约束

名称用途版本或核对条件
t文本修饰符,可与 r、w、x、a 和 + 组合。默认文本模式按指定编码读写 str。rt 与 r 等效,t 单独不是完整模式。
x独占创建新文件,默认只写。已存在时报 FileExistsError。旧 2.7 内置 open 不支持此现代模式。创建一次后再次打开会拒绝。
b二进制修饰符,与基本模式组合。读取或写入字节,不做编码或换行转换。rb 返回 bytes,b 单独无效。
+更新修饰符,使读和写都可用。文件是否新建、截断或追加仍由基本模式决定。r+ 不创建,w+ 截断,a+ 写入时追加。
UPython 2.7 的历史通用换行模式。现代文本读取使用 newline=None,3.11 已删除 U 模式。3.12 使用 U 抛 ValueError;newline=None 能统一 CRLF、CR 和 LF。
r默认只读。要求已有文件,起始位置在开头。不存在时报 FileNotFoundError。
rb只读字节。要求已有文件,从开头读取。UTF-8 汉字的字节数可能大于字符数。
r+读写已有文本文件,从开头开始。打开时保留内容。在开头写入一个字符只替换当前位置对应内容。
rb+读写已有字节文件,从开头开始,不截断。修改指定的一个字节,再核对前后字节。
w只写文本。文件不存在时创建,存在时打开即截断。打开后即使未写,旧内容也已清空。
wb只写字节。不存在时创建,存在时截断。写入 00ff,读取原字节校验。
w+读写文本。不存在时创建,存在时截断。写完 seek(0) 后读回。
wb+读写字节。不存在时创建,存在时截断。写入字节,再回到开头读回。
a只写文本。不存在时创建,存在时保留。写入追加到末尾。即使 seek(0),实测写入仍追加。
ab只写字节。不存在时创建,存在时保留并追加。原有字节后增加一个零字节。
a+可读写文本。写入仍追加。想读取旧内容时先 seek(0)。本机打开后在末尾,回到开头能读旧内容。
ab+可读写字节。写入仍追加。按字节 seek 可以读取旧内容。观察旧字节、末尾追加以及读回。

文件对象方法、返回值和异常

名称用途版本或核对条件
file.close刷新并关闭。再次关闭无额外效果,关闭后读写抛 ValueError。with 退出后检查 closed,核对文件中的原字节。
file.flush将 Python 的写缓冲送向操作系统。若要求持久化,另行按系统要求使用 fsync。第二个读者在刷新前后分别读取。
file.fileno返回可交给部分 os 接口的整数描述符。没有描述符的内存流可抛 UnsupportedOperation。比较普通文件和 BytesIO。
file.isatty查询流是否连到终端。普通文件返回 False,管道也不等同于终端。本章观察普通文件;真实终端状态单独记录。
file.next2.7 的方法读取下一行,现代使用 next(stream) 或 for。耗尽时抛 StopIteration。用两行文本逐次读取,并核对第三次。
file.read读至 size 上限;默认或负值读完剩余部分。文本计字符,二进制计字节。同样的输入前两字符和前两字节不同。
file.readline读一行并保留已有行尾,可用 size 限制长度。到达 EOF 返回空 str 或 bytes。逐步读首行的片段和剩余内容。
file.readlines返回行列表。hint 是近似总量提示,完整行可能越过阈值,后续仍可从当前位置读。用短行和长行比较提示值、完整行和余下内容。
file.seek改变当前位置并返回新位置。二进制支持字节偏移;文本定位用从 tell 获得的标记。比较三种二进制参照和文本不支持的非零相对偏移。
file.tell查询当前位置。文本返回可供 seek 恢复状态的标记,二进制返回字节偏移。读 CRLF 后保存标记并重读同一字符。
file.truncate将文件大小改到 size,省略时使用当前位置,位置本身保持。文本包装下仍应考虑字节长度。在二进制流测试显式和默认截短;扩展内容依平台另核。
file.write写入给定内容,不补换行。现代文本流返回字符数,二进制流返回字节数;旧内置 file.write 返回 None。写两个中文字符,分别记录 2 个字符和 UTF-8 的 6 个字节。
file.writelines逐项写入可迭代对象,不会自动加行尾,返回 None。手动给第二项加换行,核对文件中的精确文本。

open 的八项参数

名称用途版本或核对条件
file相对或绝对路径、path-like 对象,或已打开的整数文件描述符。相对路径以当前工作目录解释。路径形式和描述符形式分开观察。
mode省略时 r。先选基本动作,再按需加入 b、t、+。独占创建、截断和追加是不同条件。按下一表验证访问权和位置。
buffering-1 采用默认策略,0 仅用于无缓冲二进制,1 用于文本写入的行缓冲,更大的值可请求二进制缓冲大小。核对默认缓冲、无缓冲与行缓冲。
encoding选择文本与字节之间的编码;省略会使用环境默认值。二进制流不接受此参数。用 UTF-8 写中文并检查原字节。
errors选择编解码遇到无效输入时的处理方式。默认 strict,replace 以替代字符继续,ignore 会丢数据。用同一份无效 UTF-8 核对三种结果。
newline文本读取时 None 统一三种常见换行,空字符串保留原行尾;输出的换行翻译也由此参数决定。比较原始 CRLF、CR 和 LF。
closefd对路径应保持 True。传入文件描述符并设为 False,可关闭包装流后继续使用原描述符。用 os.fstat 核对两种生命周期。
opener可调用对象接收路径和打开标志,返回已打开的文件描述符;open 管理其生命周期。记录调用时的路径与只读标志,返回 os.open 的结果。

运行文件对象的参数、描述符及定位实验

python · 阅读源码
import json


def report(name, value):
    print(json.dumps([name, value], ensure_ascii=True))


def error_name(action):
    try:
        action()
    except (AttributeError, IndexError, KeyError, NameError, TypeError, ValueError) as error:
        return type(error).__name__
    return None


import io
import os
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory


def failure(action):
    try:
        action()
    except (OSError, ValueError, TypeError, StopIteration) as error:
        return type(error).__name__
    return None


with TemporaryDirectory(prefix="mbsky-stream-", dir=Path.cwd()) as name:
    root = Path(name).resolve()
    path = root/"sample.txt"
    path.write_bytes("北\r\n南\r末\n".encode("utf8"))
    with open(path, encoding="utf8", newline=None) as stream:
        default_mode = stream.mode
        translated = stream.read()
    with open(path, "rt", encoding="utf8", newline="") as stream:
        preserved = stream.read()
    with open(path, "rb", buffering=0) as stream:
        unbuffered = type(stream).__name__
        first_two = stream.read(2).hex()
    with open(path, "rb", buffering=8) as stream:
        buffered = type(stream).__name__
    with open(root/"line.txt", "w", encoding="utf8", buffering=1, newline="") as stream:
        line_buffer = stream.line_buffering
        stream.write("北\n")
        line_seen = (root/"line.txt").read_bytes().hex()

    invalid = root/"invalid.txt"
    invalid.write_bytes(b"X\xffZ")
    def decoded(errors):
        with open(invalid, encoding="utf8", errors=errors) as stream:
            return stream.read()

    def try_open(file, mode, **options):
        with open(file, mode, **options):
            return True

    fd = os.open(path, os.O_RDONLY | os.O_BINARY)
    try:
        with open(fd, "rb", closefd=False) as wrapper:
            fd_content = wrapper.read(2).hex()
        fd_retained = os.fstat(fd).st_size == path.stat().st_size
    finally:
        os.close(fd)
    fd_owned = os.open(path, os.O_RDONLY | os.O_BINARY)
    with open(fd_owned, "rb", closefd=True) as stream:
        assert stream.fileno() == fd_owned
    fd_closed = failure(lambda: os.fstat(fd_owned))
    calls = []
    def custom_opener(file, flags):
        calls.append([Path(file).name, (flags & (os.O_WRONLY|os.O_RDWR))==os.O_RDONLY])
        return os.open(file, flags)

    with open(path, "rb", opener=custom_opener) as custom:
        custom_fd=custom.fileno()
        custom_bytes=custom.read(2).hex()
    closed_after_opener=failure(lambda: os.fstat(custom_fd))
    report("open_arguments", {
        "file": [path.name,fd_content,failure(lambda: try_open(root/"missing.txt","r"))],
        "mode": [default_mode,translated],
        "buffering": [unbuffered,buffered,line_buffer,line_seen,
                      failure(lambda: try_open(path,"r",buffering=0))],
        "encoding": ["北".encode("utf8").hex(),failure(lambda: try_open(path,"rb",encoding="utf8"))],
        "errors": [failure(lambda: decoded("strict")),decoded("replace"),decoded("ignore")],
        "newline": [translated,preserved],
        "closefd": [fd_retained,fd_closed,failure(lambda: try_open(path,"rb",closefd=False))],
        "opener": [calls,custom_bytes,closed_after_opener],
    })

    exclusive=root/"exclusive.txt"
    first=try_open(exclusive,"x")
    modes={"t":[failure(lambda:try_open(path,"t")),translated],
           "b":[failure(lambda:try_open(path,"b")),first_two],
           "+":failure(lambda:try_open(path,"+")),
           "U":[failure(lambda:try_open(path,"U")),translated],
           "x":[first,failure(lambda:try_open(exclusive,"x"))]}
    for mode in ("r","rb","r+","rb+","w","wb","w+","wb+","a","ab","a+","ab+"):
        old=root/("old-"+mode)
        new=root/("new-"+mode)
        old.write_bytes(b"abc")
        binary="b" in mode
        options={} if binary else {"encoding":"utf8","newline":""}
        with open(old,mode,**options) as stream:
            start=stream.tell()
            read,write=stream.readable(),stream.writable()
            empty=old.stat().st_size==0
            stream.seek(0)
            if write:
                stream.write(b"Z" if binary else "Z")
        missing=failure(lambda:try_open(new,mode))
        modes[mode]=[read,write,empty,start,old.read_bytes().decode("ascii"),missing,new.exists()]
    report("modes",modes)

    output=root/"output.bin"
    with open(output,"wb",buffering=8) as stream:
        stream.write(b"xy")
        before=output.read_bytes().hex()
        stream.flush()
        after=output.read_bytes().hex()
        ordinary_fd=stream.fileno()
        size=os.fstat(ordinary_fd).st_size
        is_terminal=stream.isatty()
    stream.close()
    closed=[stream.closed,output.read_bytes().hex(),failure(lambda:stream.write(b"q"))]
    pipe=subprocess.run([sys.executable,"-I","-B","-c","import sys;print(sys.stdin.isatty())"],
                        input=b"",capture_output=True,check=True)
    assert not pipe.stderr
    with open(path,"r",encoding="utf8",newline=None) as stream:
        first_line=next(stream)
        second_line=next(stream)
        third_line=next(stream)
        exhausted=failure(lambda:next(stream))
    with open(path,"r",encoding="utf8",newline=None) as stream:
        by_chars=[stream.read(2),stream.read(-1),stream.read()]
    with open(path,"rb") as stream:
        by_bytes=[stream.read(2).hex(),len(stream.read())]
    with open(path,"r",encoding="utf8",newline=None) as stream:
        line_fragments=[stream.readline(1),stream.readline(),stream.readline(),stream.readline(),stream.readline()]
    hint_file=root/"lines.txt"
    hint_file.write_bytes(b"a\nbbbb\nc\n")
    with open(hint_file,"rb") as stream:
        with_hint=[line.decode("ascii") for line in stream.readlines(3)]
        remaining_lines=[line.decode("ascii") for line in stream.readlines()]
    with open(path,"r",encoding="utf8",newline=None) as stream:
        stream.read(2)
        mark=stream.tell()
        point=stream.read(1)
        stream.seek(mark)
        returned=stream.read(1)
        text_seek=failure(lambda:stream.seek(-1,1))
    with open(path,"rb") as stream:
        positions=[stream.seek(2,os.SEEK_SET),stream.seek(1,os.SEEK_CUR),
                   stream.seek(-1,os.SEEK_END),stream.tell()]
    shortened=root/"short.bin"
    shortened.write_bytes(b"abcdef")
    with open(shortened,"rb+") as stream:
        stream.seek(3)
        explicit=stream.truncate(5)
        same_after_explicit=stream.tell()
        default=stream.truncate()
        same_after_default=stream.tell()
    written=root/"written.txt"
    with open(written,"w",encoding="utf8",newline="") as stream:
        amount=stream.write("北站")
    with open(written,"ab") as stream:
        byte_amount=stream.write("北站".encode("utf8"))
    joined=root/"joined.txt"
    with open(joined,"w",encoding="utf8",newline="") as stream:
        lines_return=stream.writelines(iter(["北","南\n","西"]))
    report("methods",{
        "file.close":closed,
        "file.flush":[before,after],
        "file.fileno":[isinstance(ordinary_fd,int),size,failure(io.BytesIO().fileno)],
        "file.isatty":[is_terminal,pipe.stdout.decode().strip()],
        "file.next":[first_line,second_line,third_line,exhausted,hasattr(io.StringIO(),"next")],
        "file.read":[by_chars,by_bytes],
        "file.readline":line_fragments,
        "file.readlines":[with_hint,remaining_lines],
        "file.seek":[positions,text_seek],
        "file.tell":[isinstance(mark,int),point,returned],
        "file.truncate":[explicit,same_after_explicit,default,same_after_default,shortened.read_bytes().decode("ascii")],
        "file.write":[amount,byte_amount,written.read_bytes().hex()],
        "file.writelines":[lines_return,joined.read_text(encoding="utf8")],
    })
预期结果 · 待实际运行核验
  • 观察八项参数、缓冲前后、流关闭后的描述符状态、两种读写计数和截短。
运行文件对象的参数、描述符及定位实验

所需环境:Windows CPython 3.12

当前源码 SHA256:cca27830d5b1c02dec7540f7a95bb926b422e20ca40b9663551079ace121d6bb

下载本站示例源码

常见错误与边界

  • 核对目标解释器版本、环境条件和输入后,再比较实际输出。

练习与解答

readlines(3) 为什么可能交回多于 3 字节的结果?

展开参考解答

3 是总量提示。实现以完整行返回,最后纳入的一行可以使总量超过阈值。

规范与官方依据