ronszon ronszon -5 years ago 159
Python Question

Python: How to read a (static) file from inside a package?

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?


Answer Source

[added 2016-06-15: apparently this doesn't work in all situations. please refer to the other answers]

import os, mypackage
template = os.path.join(mypackage.__path__[0], 'templates', 'temp_file')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download