推理基础设施 · Python4.1 文本文件读写
04
文件操作与简单模块化 · 1 / 4

4.1 文本文件读写

💡 读 prompt 模板、读模型卡、读日志——一切文本文件的标配

4.1 文本文件读写

推荐写法:with open(…)

with open("path.txt", "r", encoding="utf-8") as f:
    content = f.read()           # 全部读成字符串
    lines = f.readlines()        # 按行读成 list

with open("out.txt", "w", encoding="utf-8") as f:
    f.write("hello")
    f.writelines(["a\n", "b\n"])

关键点

  • with 块结束时会自动关文件(即使中途异常)
  • encoding="utf-8" 必须显式写,否则不同平台行为不一致
  • 模式:"r" 读、"w" 写(覆盖)、"a" 追加

为什么推理代码也用

读 system prompt、读模型配置文件、读 vocab、读 few-shot 例子。

示范

# 写
with open("prompt.txt", "w", encoding="utf-8") as f:
    f.write("You are a helpful assistant.\n")

# 读
with open("prompt.txt", "r", encoding="utf-8") as f:
    print(repr(f.read()))

✍️ 练习

写代码:

  1. with open(...) 把字符串 "Qwen2.5-7B-Instruct\nvllm-0.6\n" 写到文件 model_card.txt
  2. 再用 with open(...) 把它读出来,赋值给 content,然后 print(content

注意编码用 utf-8,写模式用 "w",读模式用 "r"

💡 思路提示

点开看提示
  1. with open(path, mode, encoding="utf-8") as f: 是固定模式
  2. 读全部内容用 f.read()
  3. print(repr(content)) 能看到 \n 是否真的存在

✅ 参考解法

写不出来再打开
path = "model_card.txt"

with open(path, "w", encoding="utf-8") as f:
    f.write("Qwen2.5-7B-Instruct\nvllm-0.6\n")

with open(path, "r", encoding="utf-8") as f:
    content = f.read()

print(content)

🔍 进阶思考

f.read() 把整个文件读成一个大字符串;超大文件用 for line in f: 一行行读,内存友好。

with open("huge.log", "r", encoding="utf-8") as f:
    for line in f:
        process(line)