You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从文件向Python加载三重双引号变量?

整理Python中多行字符串变量的实践方案

首先解决你用read()读取文本文件的问题:你提到的“无法正确将内容读取为变量”,大概率是文本文件的格式和原三重引号内容不一致导致的。比如原my_prompt里的换行、缩进、开头的空行,在保存到my_prompt.txt时要完全原样保留,这样f.read()就能得到和原变量一致的内容。如果还是有问题,可以检查文件编码(确保是UTF-8),或者打印读取后的内容对比原变量,定位差异点。

下面是几种更规范的整理方案:

1. 用独立Python模块集中管理

这是最简单直接的方式,适合所有规模的prompt集合:

  • 新建一个prompts.py文件,把所有多行字符串变量都放在这里:
    # prompts.py
    my_prompt = """
    Here goes a prompt, etc.
    .....
    """
    
    user_onboarding_prompt = """
    Welcome! Let's get started...
    Step 1: ...
    """
    
  • 在主代码中直接导入使用:
    from prompts import my_prompt, user_onboarding_prompt
    
    # 使用变量
    print(my_prompt)
    

这种方式完全保留Python字符串的语法,不用处理文件读取的格式问题,还能享受IDE的语法高亮和提示。

2. 用文本文件+封装读取函数

如果必须用纯文本文件管理,建议封装一个读取函数,避免重复代码,同时统一处理格式:

def load_prompt(file_path):
    with open(file_path, "r", encoding="utf-8") as f:
        return f.read().rstrip("\n")  # 可选:移除末尾多余换行,和三重引号行为对齐

# 使用
my_prompt = load_prompt("my_prompt.txt")

注意:保存文本文件时,要和原三重引号里的内容完全一致——比如原变量里开头的换行、中间的缩进都要原样保存,这样读取后内容才会和原变量一致。

3. 用YAML配置文件管理(适合多prompt分类)

如果你的prompt数量多、需要分类管理,YAML是更友好的选择,它原生支持多行字符串:

  • 先安装依赖:pip install pyyaml
  • 新建prompts.yaml文件:
    # prompts.yaml
    system_prompts:
      general: |
        You are a helpful assistant...
        Answer questions clearly and concisely.
      code: |
        You are an experienced Python developer...
        Provide well-commented code examples.
    user_prompts:
      onboarding: |
        Hi there! I'm new here, can you walk me through...
    
  • 在代码中读取:
    import yaml
    
    with open("prompts.yaml", "r", encoding="utf-8") as f:
        prompt_data = yaml.safe_load(f)
    
    # 获取指定prompt
    general_system_prompt = prompt_data["system_prompts"]["general"]
    

YAML的|符号会保留多行字符串的换行和缩进,和Python三重引号的行为一致,而且结构清晰,方便维护。

4. 用JSON文件管理(可选)

JSON也支持多行字符串,不过需要用转义字符\n,可读性稍差,但不需要额外依赖:

  • 新建prompts.json:
    {
      "my_prompt": "\nHere goes a prompt, etc.\n.....\n",
      "another_prompt": "\nWelcome! Let's start...\n"
    }
    
  • 读取代码:
    import json
    
    with open("prompts.json", "r", encoding="utf-8") as f:
        prompt_data = json.load(f)
    
    my_prompt = prompt_data["my_prompt"]
    

这种方式适合已经在用JSON做配置的项目,但编辑多行字符串时需要手动处理转义,不如YAML方便。

内容的提问来源于stack exchange,提问作者user321627

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 08:40:14