python-3.x

How to load in triple double quoted variables into Python from a file?


I have a variable that is triple quoted which I have in Python:

my_prompt = """
Here goes a prompt, etc.
.....
"""

It gets messy to have them in my Python file one after another and I want a way to organize them. One idea I had was to save the my_prompt variable into a file and then source it. However, I am having troubles with this as something like

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

doesn't read as a variable. What are good practices and ideas for this? thanks.


Solution

  • Option 1: rename the file to my_prompt.py and import it as a module:

    from my_prompt import my_prompt
    
    
    assert my_prompt == """Here goes a prompt, etc.
    .....
    """
    

    Option 2: Store only the value in the file, then continue to read the file as you are. You can store the value to any variable you like, without putting a variable name in the file as well.

    $ echo "Here goes a prompt, etc.
    .....
    " > my_prompt.txt
    

    And the same Python code as you currently have:

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