Avid Programmer
Avid Programmer

Reputation: 145

Call a file outside of the directory from inside of a directory - Python

I have a directory which has all the files:

myDirectory/
    directory1/
        importantFile.py
    Output.py

How can I import Output.py from importantFile.py without having to put in the same directory?

importantFile.py

import Output
Output.write('This worked!')

Output.py

class Output():
    def writeOutput(s):
        print s

Upvotes: 3

Views: 1846

Answers (3)

Rolf of Saxony
Rolf of Saxony

Reputation: 22443

import sys
sys.path.append('/full/path/to/use')
global exist_importedname
exist_importedname = True
try:
    import myimport
except ImportError as e:
    exist_importedname = False
    print (e.message)

Upvotes: 0

sahitya
sahitya

Reputation: 5538

The other way is to use the relative notation, for which the python file you want to import should be in a package.

You have to make the directory a python package by putting an init.py file.

Look for the packages section in this link.

https://docs.python.org/2/tutorial/modules.html

Upvotes: 0

Bruce
Bruce

Reputation: 7132

if "call" is import, in Output.py

import sys
import os.path
# change how import path is resolved by adding the subdirectory
sys.path.append(os.path.abspath(os.getcwd()+'/directory1'))
import importantFile

importantFile.f()

sys.path contains the list of path where to look for modules, details in https://docs.python.org/2/library/sys.html

Upvotes: 1

Related Questions