xxx222
xxx222

Reputation: 3244

How to call functions in python files that are not in the working directory?

Say now my working folder is . and my supporting python files are in ./supporting_files/, I want to call a function func in the a.py file under ./supporting_files/, what should I do? I tried calling from supporting_files.a import func and that does not work. How am I suppose to do that without changing the actual working directory?

Upvotes: 2

Views: 226

Answers (2)

Wayne Werner
Wayne Werner

Reputation: 51807

There are two ways you can do that I'm aware of.

Wrong way

import sys
sys.path.append('./supporting_files')    
from a import func
func()

Right way

$ touch supporting_files/__init__.py

Then

import supporting_files.a as a

a.func()

Upvotes: 3

nthall
nthall

Reputation: 2915

Add an __init__.py file (it can be empty) to the supporting_files directory, and python will treat it as a package available for imports. More details are available in the Python documentation.

Upvotes: 1

Related Questions