importing out of cwd

Alex Martelli aleaxit at yahoo.com
Sat Sep 9 18:40:54 EDT 2000


"Neil Macneale" <macneale at cats.ucsc.edu> wrote in message
news:macneale-0909001410110001 at 192.168.1.24...
>
>
> What is the syntax to import something that is not in the current working
> directory.  Specifically I want to import something from one directory up.
>
> This works from the command line:
>
> >>>import os
> >>>os.chdir("..")
> >>>import what_I_want_to_import
> >>>os.chdir("DIRECTORY_I_WANT_TO_BE_IN")
>
> The reason I don't like this is that I want to put it all in a script that
> won't necessarily be in the correct working directory.  the code:
>
> >>> import ../what_I_want_to_import
>
> does not seem to work. There must be some way to do this (without adding
> the top directory to my puthon path) that I have missed.

You do have to temporarily add to sys.path the directory you want,
before importing; then, you can take it off again.  This should work:

    import sys
    sys.path = [".."] + sys.path
    import whatever
    sys.path = sys.path[1:]


Alex






More information about the Python-list mailing list