2

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?

5
  • Do you have the __init__.py in supporting_files directory? What's your python version? Commented Jul 15, 2016 at 20:44
  • No I don't have one. It's python 2.7 Commented Jul 15, 2016 at 20:45
  • works for me, cannot reproduce. edit: works in python3 but not in 2.7 Commented Jul 15, 2016 at 20:45
  • 1
    You need to put an empty __init__.py in your directory in order to be interpreted as a module, by python. Commented Jul 15, 2016 at 20:46
  • 1
    Python 2 tutorial chapter 6 on modules Commented Jul 15, 2016 at 20:47

2 Answers 2

3

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()
Sign up to request clarification or add additional context in comments.

2 Comments

I mean it works, but works in kind of the same way that a Rube Goldberg machine works. It's fine for entertainment/education but you wouldn't ever want to drive your space program that way.
Thanks I think I got it
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.