I have my program set up using packages as followed:
-base
-init.py
-base_class.py
-test
-init.py
-test.py
When I do the import statement from base.base_class import BaseClass in the test.py I get this error when running it:
from base.base_class import BaseClass
ImportError: No module named base.base_class
How can I import this module?
at the top of test.py add
import sys
sys.path.append("..")
base is not a folder on the path...once you change this it should work
or put test.py in the same folder as base. or move base to somewhere that is on your path
you nee to have an __init__.py file in each folder you import from
You have to create a file called "__init__.py" at python directories, then "the Python" will understand that directory as a Python package.
there are 3 things you can do:
add an init.py file to each folder
add sys.path.append("Folder") to the top
or use imp and do;
import imp
foo = imp.load_source('filename', 'File\Directory\filename.py')
then foo will be the name of the module for example foo.method()
Related
I have this project structure,
.\src
.\api
test.py
.\config
config.py
app.py
when i'm trying to import a function or class from test.py inside config.py, using this statement
from src.api.test import tes_func
I get this error
ModuleNotFoundError: No module named 'src.api'
if i use these 2 lines i can import using
from api.test import tes_func.
import sys
sys.path.append("../")
why it's not working when use from src.api.test import test_func
Is there a way to import python files without sys.path.append("../").
Thanks in advance.
You need to change the working directory.
Before python was only able to see other files inside the config folder.
If you run your program from a common parent directory python is able to see both folders and there files.
..\PycharmProjects\pythonProject> python -m src.config.config
My folder structure:
With this command src is now your root directory meaning in config.py you will need to import the function like this:
from src.api.test import tes_func
I wanted to make a cmd tool. I created two files, one named main.py, and the other named version.py
there are in the same directory
version.py:
import os
def pyVersion():
os.system("python --version")
main.py:
import version
version.pyVersion()
I think it should work, but when I run main.py, it prints:
File "C:\Users\User\PycharmProjects\cmd tool\main.py", line 1, in <module>
import version
ModuleNotFoundError: No module named 'version'
Normally Python should use folder C:\Users\User\PycharmProjects\cmd tool\ to search imported modules and you may have this folder even on list sys.path
But if it doesn't have this folder on list then you may add it manually before importing module.
import sys
# add at the end of list
#sys.path.append(r'C:\Users\User\PycharmProjects\cmd tool\')
# add at the beginning of list
sys.path.insert(0, r'C:\Users\User\PycharmProjects\cmd tool\')
import version
# ... code ...
To make it more universal you can use os to get this folder without hardcoding
import os
BASE = os.path.dirname(os.path.abspath(__file__))
print('BASE:', BASE)
import sys
sys.path.insert(0, BASE)
import version
# ... code ...
Just import file without the .py extension.
A folder can be marked as a package, by adding an empty __init__.py file.
You can use the __import__ function, which takes the module name (without extension) as a string extension.
change please the class name , and make the first letters uppercase
Version.py
def pyVersion():
os.system("python --version")
Main.py
import Version
Version.pyVersion()
and the code must work and he will give you a result Python version
I have a structure such has:
/mainfolder
file.py
//subfolder
test.py
I am trying to import file.py in test.py. for some reason I just can't.
I tried
from .file import *
returning :
Traceback (most recent call last):
ModuleNotFoundError: No module named '__main__.file'; '__main__' is not a package
also tried to add path to sys.path:
import sys
import os
sys.path.extend([os.getcwd()])
doesnt work either
Looks like you're running test.py with python test.py and as such the test module is being treated as a top level module.
You should first make your folders Python packages if they are not by adding __init__.py files:
/mainfolder
__init__.py
file.py
/subfolder
__init__.py
test.py
Then you can append the outer mainfolder to sys.path:
import sys
import os
sys.path.append(os.path.join(os.getcwd(), '..'))
After which from file import someobject without relative import works. Be wary of wild card imports.
See ModuleNotFoundError: What does it mean __main__ is not a package? and How to do relative imports in Python? for more on why your current approach does not work.
What IDE are you using? I am using Pycharm Community IDE with Python 3 and it works with from file import * or from file import some_function (I wanted to comment but I can't since I don't have 50 reputation yet)
I am using Python 3.4
I have a directory structure that looks this:
A
B
c.py
d.py
__init__.py
C
e.py
f.py
__init__.py
g.py
__init__.py
From g.py I can import things from both B and C modules.
I need, in e.py, to import something from c.py
I tried:
import B
and
from B.c import stuff_I_need
For both I get the error:
"No module named B".
I also tried something like:
from A.B.c import stuff_I_need
I am further confused by the fact with an identical directory structure, I can make the imports I need with Python 2.7.
Can you help me figure out what's going on?
Solution:
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
Taken from here.
When importing it looks at the the python folder for imports and the files in the local directory. If you want to import a file that is in neither of those, then I suggest using the sys module
import sys
sys.path.append(r'file-path\A') # Folder A
import B.c
If you don't want to set the full file path then you can also just backtrack to the previous directory with this for the same effect.
sys.path.append('..') # Previous Directory
You need to do either
from .B import c
or
import A.B.c
Reference:
What's New in Python 2.5
PEP 328 - Imports: Multi-Line and Absolute/Relative
I have a Python 3 project that's structured like this:
/project
__init__.py
/models
__init__.py
my_model.py
base_model.py
/tests
__init__.py
test.py
In test.py I want to import my_model. My first attempt was from models import my_model, which threw an ImportError: No module named 'models'. This question recommended adding an __init__.py file to each directory, which didn't help. Another post said to modify the path with:
import sys; import os
sys.path.insert(0, os.path.abspath('..'))
but this throws an error when my_model tries to import from base_model.
This seems really straightforward but I'm stumped. Does anyone have any ideas?
Adding the sibling directory to sys.path should work:
import sys, os
sys.path.insert(0, os.path.abspath('../models'))
import my_model
Use absolute imports everywhere: from project.models import my_model, should work fine from wherever in your project, no need to mess with paths either.
The answer depends on how you launch test.py.
The only way I know to do relative imports is to have the file in a package. For the Python interpreter to know you're in a package is to import it in some way.
Use:
from ..models import my_model
in test.py
And launch the Python Interpreter below the project folder.
You will then be able to import project.tests.test without error.