python resource embedding

This is how to embed a resource in a python module

This Module will be call Bob

Start PyCharm

  • New Project
    • Bob

Open Pycharm

  • New Package
    • Bob

Write Main code

  • make sure the class is inside the Bob Package
  • you data file "tim.txt" is also into the Bob Package

Build the Package

  • in the IDE Tools -> Setup.py

It will look something like this

from distutils.core import setup

setup(
    name='bob',
    version='',
    packages=['bob'],
    url='',
    license='',
    author='timothyhseed',
    author_email='a45wg@sy-edm.com',
    description=''
)

Command line time

  • python setup.py build
  • python setup.py install

Update the Build

In the IDE

  • Create a directory in the Build folder called data
  • Copy tim.txt to Build/data

Modify Main Code

instead of

open('tim.txt','r')

replace with

import pkgutil
f=pkgutil.get_data('bob','/data/tim.txt')

Update the Build

  • python setup.py build
  • python setup.py install

And that should be it !!