Importing from upper directory

Gary Herron gherron at digipen.edu
Sat Feb 17 13:57:08 EST 2007


Harlin Seritt wrote:
> I have a script that I want to import called upper.py. It is 2
> directories above the script that will call it - i'll call that one
> main.py. How am I able to import a script in a directory that is above
> it?
>
> Thanks,
>
> Harlin
>   
You can control the directories from which Python imports by modifying 
the sys.path attribute. Something like this:

import sys
sys.path.append("../..") #That's two directories up from the current 
directory
import upper

If you're unsure what the current working directory is, try:

import os
print os.getcwd() # The current working directory

If it's not the current directory, but rather the directory containing 
the original script you want, then

import sys, os
path = sys.argv[0] #Initial script name
path0 = os.path.split(path)[0] #Initial script path
path1 = os.path.split(path0)[0] # Up one
path2 = os.path.split(path1)[0] # Up two
sys.append(path2)

Gary Herron






More information about the Python-list mailing list