how to organize a module that requires a data file

Paul Boddie paul at boddie.org.uk
Thu Nov 17 14:36:10 EST 2005


Steven Bethard wrote:

[Text file for a module's internal use.]

> My problem is with the text file.  Where should I keep it?  If I want to
> keep the module simple, I need to be able to identify the location of
> the file at module import time.  That way, I can read all the data into
> the appropriate Python structure, and all my module-level functions will
> work immediatly after import.

I tend to make use of the __file__ attribute available in every module.
For example:

resource_dir = os.path.join(os.path.split(__file__)[0], "Resources")

This assigns to resource_dir the path to the Resources directory
alongside the module itself in the filesystem. Of course, if you just
wanted the text file to reside alongside the module, rather than a
whole directory of stuff, you'd replace "Resources" with the name of
your file (and change the variable name, of course). For example:

filename = os.path.join(os.path.split(__file__)[0],
"morph_english.flat")

Having posted this solution, and in the tradition of Usenet, I'd be
interested to hear whether this is a particularly bad idea.

Paul




More information about the Python-list mailing list