首页 › Python 实例 › 文件写入与读取

Python 文件写入与读取

日期与文件实例 035

题目

把数据写入文本文件,再逐行读取并统计行数和字数。示例在临时目录中运行,不会留下文件。

参考代码

import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "poem.txt"
    lines = ["床前明月光", "疑是地上霜", "举头望明月", "低头思故乡"]
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")

    with open(path, encoding="utf-8") as f:
        for no, line in enumerate(f, 1):
            print(f"{no}: {line.rstrip()}")

    text = path.read_text(encoding="utf-8")
    print("行数:", text.count("\n"), " 字数:", len(text.replace("\n", "")))

    with open(path, "a", encoding="utf-8") as f:
        f.write("—— 李白《静夜思》\n")
    print("追加后最后一行:", path.read_text(encoding="utf-8").splitlines()[-1])
执行以上代码输出结果为:
1: 床前明月光
2: 疑是地上霜
3: 举头望明月
4: 低头思故乡
行数: 4  字数: 20
追加后最后一行: —— 李白《静夜思》

代码解析

open 的模式:r 读、w 写(覆盖)、a 追加。始终显式指定 encoding="utf-8",否则在 Windows 上可能出现中文乱码。用 with 打开文件能保证文件被正确关闭。