Skip to content

Python 标准库:文件、数据与时间 ​

文件与结构化数据 ​

pathlib 表达路径,json 处理 JSON,csv 处理 CSV。文本明确编码;CSV 文件用 newline="" 交给模块处理换行。下面使用临时目录,运行后自动清理,不改写当前目录文件。

python
import csv
import json
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    root = Path(directory)
    people = [{"name": "Alice", "age": 25}, {"name": "小明", "age": 30}]
    source = root / "people.json"
    source.write_text(json.dumps(people, ensure_ascii=False), encoding="utf-8")
    loaded = json.loads(source.read_text(encoding="utf-8"))
    assert loaded == people

    target = root / "people.csv"
    with target.open("w", encoding="utf-8", newline="") as stream:
        writer = csv.DictWriter(stream, fieldnames=["name", "age"])
        writer.writeheader()
        writer.writerows(loaded)
    with target.open(encoding="utf-8", newline="") as stream:
        rows = list(csv.DictReader(stream))
    assert rows[0] == {"name": "Alice", "age": "25"}

CSV 读出通常是字符串,类型转换需显式处理;json.loads 对非法 JSON 抛 JSONDecodeError。大文件不要无条件一次性 read_text() 后全放内存。

解释器、数学、时间与正则 ​

模块常用入口边界
syssys.argv、sys.executable参数含脚本名;解释器路径用于排查环境
os环境变量、进程接口路径处理也可用 pathlib
mathsqrt、ceil、isclose浮点数比较考虑误差
randomrandint、choice模拟与抽样;安全令牌用 secrets
datetime带时区的时间、timedelta存储与显示时明确时区
research、findallsearch 返回 Match 或 None,取组前先检查;findall 返回列表,无匹配时为 []
python
import math
import re
from datetime import datetime, timezone

assert math.isclose(0.1 + 0.2, 0.3)
now = datetime.now(timezone.utc)
assert now.tzinfo is not None
match = re.search(r"hello\s+(\w+)", "hello world")
assert match is not None and match.group(1) == "world"

网络操作单独执行 ​

网络示例需要可达服务;超时、HTTP 错误、响应编码应由调用方处理。不要把联网请求与本地文件练习硬拼成“完整程序”。

python
from urllib.request import urlopen


def read_page(url):
    with urlopen(url, timeout=5) as response:
        charset = response.headers.get_content_charset() or "utf-8"
        return response.read().decode(charset)

urllib 适合基本 HTTP 操作。更底层 TCP 用 socket,需约定消息边界;一次 recv(1024) 不保证收到完整消息,不能把单次读写示例当作完整协议实现。

练习与资料 ​

把 JSON → CSV 示例改成函数,覆盖中文、空列表、缺少字段和无效 JSON。继续阅读 标准库参考、urllib.request,语言基础学完后,如需组织并发 I/O,再选择 线程与协程实践。

参考解答 ​

先确定缺字段策略:这里选择拒绝,避免DictWriter默默补成空字段。以下是完整纯转换函数,调用者负责文件读写:

python
import csv
import json
from io import StringIO


def json_to_csv(text):
    people = json.loads(text)
    if not isinstance(people, list):
        raise ValueError("expected a list")
    if any(not isinstance(row, dict) or set(row) != {"name", "age"}
           for row in people):
        raise ValueError("expected name and age fields")
    output = StringIO(newline="")
    writer = csv.DictWriter(output, fieldnames=["name", "age"], lineterminator="\n")
    writer.writeheader()
    writer.writerows(people)
    return output.getvalue()

[]预期只输出表头 name,age\n;中文按原文本保留;缺字段或多字段按ValueError拒绝;无效JSON抛JSONDecodeError。该函数只检查行结构,姓名类型和年龄范围尚未定义,不应据此宣称完成业务schema校验。参考未执行。

继续阅读