benalbert342
benalbert342

Reputation: 71

Import function from a .py file stored in a different folder in the same directory

I have what I believe to be a very simple question but I cannot solve it because I am unfamiliar with python. I have a project where all of the file are stored in the same directory, however different files are stored in different folders with in that directory. In particular I have one folder titled functions which stores all of the functions that I need to import into the python script that performs the analysis (this is a very simple procedure in R). I cannot get python to import the functions from the script in the functions folder.

I have tried the following:

import sys
sys.path.insert(1,'/myproject/functions/')
from functions.function import function

In the functions folder there is a file titled function.py. However, when I run this code I get the following error:

ImportError: No module named functions.function

I am not sure how to resolve this error. However it seems like import functions from a .py file stored in another directory would come up quite frequently. Is there a simple fix to this problem?

Upvotes: 0

Views: 714

Answers (2)

HarryS
HarryS

Reputation: 312

Additionally, you should also check for the name of the 'function' (located within the function.py file) you're trying to call. Then use the statement:

from functions.function import <name of actual function>

Upvotes: 0

Dave Benson
Dave Benson

Reputation: 161

You should import it as function, not functions.function. You must not write the directory of the module, only the name of the file. (Except for packages,but that's a different thing)

Upvotes: 1

Related Questions