How to include text within a python file
Question: There are several questions related to reading python code from external
files, including

[Python: How to import other Python
files](http://stackoverflow.com/questions/2349991/python-how-to-import-other-
python-files)

[How to include external Python code to use in other
files?](http://stackoverflow.com/questions/714881/how-to-include-external-
python-code-to-use-in-other-files)

But it's not clear how to include snippets of text from an external file, as
is standard practice with the CPP `#include` directive. For example, the
following code:

    
    
    def get_schema():
        schema1 = \
    {
        "$schema": "http://json-schema.org/draft-04/schema#",
        "id": "0",
        "type": "object",
        "properties": {
            "i": { "type": "integer" },
            "n": { "type": "string" }
        }
    }
        return(schema1)
    
    s = get_schema()
    print(s)
    

returns the expected dict:

    
    
    {'id': '0', '$schema': 'http://json-schema.org/draft-04/schema#', 'type': 'object', 'properties': {'i': {'type': 'integer'}, 'n': {'type': 'string'}}}
    

But what I want to do is write the code so that it imports variable
definitions from external files that do not include any python code (function
definitions or variable assignments):

    
    
    def get_schema():
        schema1 = \
    #include "schema1.json"
        return(schema1)
    
    s = get_schema()
    print(s)
    

I'm sure this could be done with a bunch of code to open the definition files,
read the contents into a string, add pre- and post-amble lines of python, and
then exec the string, but it seems that there should be a simpler way to just
include text in a function definition. Is there?


Answer: If you want to load json from a file you can use
[**`json`**](https://docs.python.org/2/library/json.html#json.load) library:

    
    
    import json
    
    def get_schema():
        with open('schema1.json', 'r') as f:    
            return json.load(f)
    

