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

运行输入、文件模式和目录操作

PYTHONPython 3.12 / Windowslegacy-file-io-lab.py
legacy-file-io-lab.py174 行
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 sys
from contextlib import redirect_stdout
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch


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


if sys.argv[1:] == ["--stdin"]:
    text = input("读数 > ")
    print(type(text).__name__, text)
    raise SystemExit

printed = io.StringIO()
with redirect_stdout(printed):
    print("北站", 7, sep=" / ", end="。\n")
report("printed_output", printed.getvalue())

prompt = io.StringIO()
with patch("sys.stdin", io.StringIO("北站 7\n")), redirect_stdout(prompt):
    line = input("读数 > ")
    ended = exception_name(input)
report("stdin_text", [line, prompt.getvalue(), ended])
with patch("sys.stdin", io.StringIO("7\n2+5\n")):
    integer = int(input())
    expression = input()
report("input_migration", [integer, expression, exception_name(lambda: int(expression))])

with TemporaryDirectory(prefix="mbsky-io-", dir=Path.cwd()) as directory:
    root = Path(directory).resolve()
    path = root / "station.txt"
    path.write_bytes(b"abcd")

    def attempt(mode, selected=path):
        with selected.open(mode):
            return True

    text_buffer = root/"buffer.txt"
    with text_buffer.open("w", encoding="utf8", buffering=1, newline="") as stream:
        first = [stream.line_buffering, stream.write("北\n"), text_buffer.read_bytes().hex()]
    with text_buffer.open("rb", buffering=0) as stream:
        raw_buffer = [type(stream).__name__, stream.read().hex()]
    with text_buffer.open("rb", buffering=8) as stream:
        explicit_buffer = [type(stream).__name__, stream.read().hex()]
    with text_buffer.open(encoding="utf8", buffering=-1) as stream:
        default_mode = [stream.mode, stream.read()]
    report("open_arguments", {
        "file_name": path.name,
        "access_mode": default_mode,
        "buffering": [exception_name(lambda: open(path,"r",buffering=0)), first, raw_buffer, explicit_buffer],
    })

    path.write_bytes("北\r\n南\r末\n".encode("utf8"))
    with path.open("rt", encoding="utf8", newline=None) as stream:
        universal = stream.read()
    with path.open("rb") as stream:
        binary_sample = stream.read(2).hex()
    mode_cases = {
        "t": [exception_name(lambda: attempt("t")), universal],
        "x": None,
        "b": [exception_name(lambda: attempt("b")), binary_sample],
        "+": exception_name(lambda: attempt("+")),
        "U": [exception_name(lambda: attempt("U")), universal],
    }
    exclusive = root/"exclusive.txt"
    created = attempt("x",exclusive)
    mode_cases["x"] = [created, exception_name(lambda: attempt("x",exclusive))]
    matrix = {}
    for mode in ("r", "r+", "w", "w+", "a", "a+", "rb", "rb+", "wb", "wb+", "ab", "ab+"):
        item = root / ("sample-"+mode.replace("+","-update"))
        missing = root / ("new-"+mode.replace("+","-update"))
        item.write_bytes(b"abcd")
        binary = "b" in mode
        extra = {} if binary else {"encoding":"utf8","newline":""}
        with item.open(mode, **extra) as stream:
            start = stream.tell()
            can_read, can_write = stream.readable(), stream.writable()
            contents_at_open = item.read_bytes().decode("ascii")
            read_initial = stream.read(1) if can_read else exception_name(lambda: stream.read(1))
            if isinstance(read_initial, bytes):
                read_initial = read_initial.decode("ascii")
            stream.seek(0)
            payload = (b"\0" if mode in ("wb", "wb+", "ab", "ab+") else b"Z") if binary else "Z"
            write_result = stream.write(payload) if can_write else exception_name(lambda: stream.write(payload))
        outcome = [start,read_initial,write_result,item.read_bytes().hex(),
                   exception_name(lambda: attempt(mode,missing)),missing.exists()]
        mode_cases[mode] = outcome
        matrix[mode] = [can_read,can_write,missing.exists(),contents_at_open=="",start==0,start==4]
    report("modes", mode_cases)
    keys = ["读","写","创建","覆盖","指针在开始","指针在结尾"]
    report("grid", {key:[matrix[mode][i] for mode in ("r","r+","w","w+","a","a+")]
                   for i,key in enumerate(keys)})

    with path.open("w", encoding="utf8", newline="") as stream:
        alias = stream
        stream = None
        state_before = alias.closed
        amount = alias.write("北站")
        attrs = [alias.mode,Path(alias.name).name,hasattr(alias,"softspace")]
    report("attributes", {"file.closed":[state_before,alias.closed],
                          "file.mode":attrs[0],"file.name":attrs[1],"file.softspace":attrs[2]})
    report("close_flush",[path.read_bytes().hex(),alias.closed,exception_name(lambda: alias.write("南"))])
    report("write_result",[amount,path.read_text(encoding="utf8"),path.read_bytes().hex()])
    path.write_bytes("北\r\n南".encode("utf8"))
    with path.open("r", encoding="utf8", newline=None) as stream:
        first_chars=stream.read(2)
        mark=stream.tell()
        remainder=stream.read()
        stream.seek(mark)
        restored=stream.read(-1)
        stream.seek(0)
        reset=stream.read(1)
        bad_seek=exception_name(lambda: stream.seek(-1, 1))
    with path.open("rb") as stream:
        first_bytes=stream.read(2).hex()
        before=stream.tell()
        stream.seek(1,1)
        after=stream.tell()
        stream.seek(-1,2)
        end_byte=stream.read(1).hex()
        stream.seek(0,0)
        reset_bytes=stream.read(2).hex()
    report("read_result",[first_chars,remainder,first_bytes])
    report("positioning",[restored,reset,bad_seek,before,after,end_byte,reset_bytes])

    changed=root/"renamed.txt"
    os.rename(path,changed)
    other=root/"existing.txt"
    other.write_text("原",encoding="utf8")
    collision=exception_name(lambda: os.rename(changed,other))
    report("rename",[path.exists(),changed.exists(),collision,other.read_text(encoding="utf8")])
    os.replace(changed,other)
    os.remove(other)
    report("remove",[other.exists(),exception_name(lambda: os.remove(other))])
    child=root/"work"
    os.mkdir(child)
    report("mkdir",[child.is_dir(),exception_name(lambda: os.mkdir(child))])
    original=Path.cwd()
    try:
        os.chdir(child)
        report("chdir",Path.cwd()==child)
        report("getcwd",Path(os.getcwd()).name)
        (child/"owned.txt").write_text("临时",encoding="utf8")
    finally:
        os.chdir(original)
    nonempty=exception_name(lambda: os.rmdir(child))
    os.remove(child/"owned.txt")
    os.rmdir(child)
    report("rmdir",[nonempty,child.exists(),Path.cwd()==original])
本例需在 Python 3.12 / Windows 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python 3.12 / Windows

入口文件:projects/python-legacy-lab/legacy-file-io-lab.py

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

下载课程关联工程包:Python2.x

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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