Search code examples
pythonmodulepkg-resources

Calculate directory path in Python module distribution


I have a Python module distribution (it's an egg) that contains some additional files & directories that I would like to copy during my program's runtime.

├── mypkg
│   ├── extra_files
│   │      ├── layouts/
│   │      ├── scripts/
│   │      └── config.yaml

When mypkg is being used, I would like to copy all contents of extra_files directory to somewhere else on disk. Something like:

shutil.copytree('mypkg/extra_files', destination)

I've taken a look at pkg_resources however it seem like I can't calculate the path to a directory that way.

How can I calculate the path to files and directories in my distribution package? Do I need to first list all directories and then call pkg_resources.resource_stream on each file in each directory?


Solution

  • I was able to actually do this with __file__, which returns the pathname from which the module was first loaded. I can get the full path to my static directory like this:

    import os
    directory = os.path.join(os.path.dirname(__file__), 'templates/index.html')