Categories
Python Answers

How to read a static file from inside a Python package?

Spread the love

Sometimes, we want to read a static file from inside a Python package.

In this article, we’ll look at how to read a static file from inside a Python package.

How to read a static file from inside a Python package?

To read a static file from inside a Python package, we can use the importlib.resources library.

For instance, we write

try:
    import importlib.resources as pkg_resources
except ImportError:
    import importlib_resources as pkg_resources

from . import templates 

template = pkg_resources.read_text(templates, 'temp_file')

to import our package with

from . import templates 

Then we read our static file with

template = pkg_resources.read_text(templates, 'temp_file')

We can also open the static file as a file with

template = pkg_resources.open_text(templates, 'temp_file')

Conclusion

To read a static file from inside a Python package, we can use the importlib.resources library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *