How to read file during module import?
gagsl-py2 at yahoo.com.ar
Fri Apr 9 18:02:45 EDT 2010
En Fri, 09 Apr 2010 18:04:59 -0300, Jeremy <jlconlin 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__))
so you could open your supporting file using:
fn = os.path.join(module_dir, "supporting_file_name.ext")
> 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"?
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)
# unpickle it
with open(filename, "rb") as f:
some_object = pickle.load(f)
Try again and report any problem you encounter...
More information about the Python-list