How to read file during module import?

Jeremy jlconlin at gmail.com
Sat Apr 10 00:16:14 CEST 2010


On Apr 9, 4:02 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
> En Fri, 09 Apr 2010 18:04:59 -0300, Jeremy <jlcon... at gmail.com> escribió:
>
> > 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.
>
> The directory containing the current module is:
>
> module_dir = os.path.dirname(os.path.abspath(__file__))

I didn't know about  __file__ this works!  Thanks.
>
> so you could open your supporting file using:
>
> fn = os.path.join(module_dir, "supporting_file_name.ext")
> open(fn) ...
>
> > 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.)
>
> What kind of "custom classes"?

My custom classes are not very fancy.  They basically are dictionaries
and lists organizing the data in the supporting file.  I was actually
surprised they didn't pickle because the classes were so simple.

> An open file, or a socket, are examples of non pickleable objects; most  
> other basic built-in objects are pickleable. Instances of user-defined  
> classes are pickleable if they contain pickleable attributes. Micro recipe:
>
> # pickle some_object
> with open(filename, "wb") as f:
>    pickle.dump(some_object, f, -1)

When I did this I got the following error:

PicklingError: Can't pickle <class '__main__.element'>: it's not found
as __main__.element

Am I just being dumb?

Thanks,
Jeremy



More information about the Python-list mailing list