tafa
tafa

Reputation: 1

How to Import Python Code from Other Files

I have a simple situation on a linux system:

ls test_repo

example  __init__.py  text

In text directory, I just have 2 files:

__init__.py ex.py

In example directory, I have just 2 files again:

__init__.py test.py

In ex.py I have the code:

def test():
    print(10)

Now, in text directory I want to import it:

from text.ex import test

print(test())

But when I run the file in the example directory as well as out of it: python test.py

I get the error:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from text.ex import test
ModuleNotFoundError: No module named 'text'

How can I import the function?

Should I put something in __init__.py?

Upvotes: 0

Views: 78

Answers (3)

GA Faza
GA Faza

Reputation: 61

In your case, you might add this into the very beginning line of your test.py

import sys
sys.path.insert(0, "..")

Because your test.py is located inside example directory not the root directory.

Upvotes: 0

Rajith Thennakoon
Rajith Thennakoon

Reputation: 4130

For everyone having this import issue,let me explain how this work

first when you import certain module to a file,how does it know where to find the module? when we import module,python check for that module in multiple locations.those locations are in sys.path. If you print sys.path it will give a list of locations where python checks when we run an import statement. in my machine output looks like this enter image description here

so what are the values in this list

  1. first value is just directory where my current script running
  2. next values are directories listed in the python path environment variable
  3. Standard library directories
  4. site packages directory for third party packages

so python check all these location when you run an import.

when you run python test.py inside the example directory,this is what happens

  1. Python add location where your current script running to the sys.path list (which is test_repo/example)
  2. test.py file has import statement from text.ex module
  3. Python search through all sys.path list to load text.ex module
  4. since ex.py file is inside the test_repo/text module and sys.path doesn't have the location for the test_repo/text it will gives the error No module named 'text'

Upvotes: 0

user12166702
user12166702

Reputation:

Look at this question, on StackOverflow. It has multiple examples for importing files, so just use the one that best fits in your situation.

Upvotes: 1

Related Questions