How to read file during module import?

Dave Angel davea at ieee.org
Sat Apr 10 07:15:48 EDT 2010


Jeremy wrote:
> I have a module that, when loaded, reads and parses a supporting
> file.  The supporting file contains all the data for the module and
> the function that reads/parses the file sets up the data structure for
> the module.
>
> How can I locate the file during the import statement.  The supporting
> file is located in the same directory as the module, but when I import
> I get a No such file or directory error.  I could hard code the path
> to the filename, but that would make it only work on my machine.
>
> A related question: Can I parse the data once and keep it somewhere
> instead of reading the supporting file every time?  I tried pickling
> but that wouldn't work because I have custom classes.  (Either that or
> I just don't know how to pickle—this is a highly probable event.)
>
> Thanks,
> Jeremy
>
>   
By supporting file, presumably you mean a text or binary file, not a 
python module. That's why import won't work.

Now, if the data supports it, you could make that supporting file simply 
be an importable python program. I've seen code generators to create 
python code from a binary file such as a jpeg, so that you can just 
embed such code into your program.

But I'll guess that this isn't reasonable for your data, that the format 
is something you want to separately manipulate.

I think the secret you're looking for is the __file__ attribute of a 
module. That contains the full path to the module source file (.py or 
.pyc, usually). So you use dirname on that string, to get the directory 
name, and os.path.join to combine with your own filename. Now you have a 
string to pass to open().

DaveA




More information about the Python-list mailing list