Python: How to read a (static) file from inside a package?
Question: Could you tell me how can I read a file that is inside my python package?

I have a following situation: a package that I load has a number of templates
(text files used as strings) that I want to load from within the program. But
how do I specify the path to such file? Imagine I want to read a file from:
package\templates\temp_file

Some kind of path manipulation? Package base path tracking?

Thanks,


Answer: Assuming your template is located inside your module's package at this path:

    
    
    <your_package>/templates/temp_file
    

the correct way to read your template is to use
[`pkg_resources`](http://pythonhosted.org/setuptools/pkg_resources.html#basic-
resource-access) package from _setuptools_ distribution:

    
    
    import pkg_resources
    
    resource_package = __name__  # Could be any module/package name
    resource_path = '/'.join('templates', 'temp_file')  # Do not use os.path.join(), see below
    
    template = pkg_resources.resource_string(resource_package, resource_path)
    # or for a file-like stream:
    template = pkg_resources.resource_stream(resource_package, resource_path)
    

> **Tip:**  
>  This will read data even if your distribution is zipped, so you may set
> `zip_safe=True` in your `setup.py`, and/or use the long-awaited [`zipapp`
> packer](https://docs.python.org/3.5/library/zipapp.html#module-zipapp) from
> _python-3.5_ to create self-contained distributions.

According to the Setuptools/`pkg_resources` docs, do not use `os.path.join`:

> ### [Basic Resource
> Access](https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-
> resource-access)
>
> Note that resource names must be `/`-separated paths and cannot be absolute
> (i.e. no leading `/`) or contain relative names like "`..`". Do _not_ use
> `os.path` routines to manipulate resource paths, as they are _not_
> filesystem paths.

