I have no idea why my import doesnt work.
My folder structure
Garage_Parking
__init__.py
database.py
rpi_components
__init__.py
NFC_Security.py
I want to import database in NFC_Security.py.
I typed
from Garage_Parking import database
It just keep giving me this error
Traceback (most recent call last):
File "NFC_Security.py", line 6, in <module>
from Garage_Parking import database
ImportError: No module named Garage_Parking
I appreciate any help.
The idea is to add the path of the parent folder to the python path so that the interpreter knows that it should look for files and modules even in the parent directory.
import os,sys
current_directory = os.getcwd()
parent_directory = os.path.dirname(current_directory)
sys.path.insert(0, parent_directory)
The code above adds the parent directory to the python path. Now you can freely import all modules from the parent folder.
Complete code for your specific case:
import os,sys
current_directory = os.getcwd()
parent_directory = os.path.dirname(current_directory)
sys.path.insert(0, parent_directory)
import database
For more information visit
Importing modules from parent folder
You could try putting the main file with the rest of the files and then doing import database. It is the easy way. If you would like to keep your folder organization, I can’t help you.
Related
I have a python project a folder structure like this:
main_directory
main.py
drivers
__init__.py
xyz.py
utils
__init__.py
connect.py
I want to import connect.py into xyz.py and here's my code:
from utils import connect as dc
But I keep getting this error no matter what I do, please help:
ModuleNotFoundError: No module named 'utils'
Update: People are telling me to set the path or directory, I don't understand why I need to do this only for importing file. This is something that should work automatically.
In your utils folder __init__.py should be blank. If this doesn't work, try adding from __future__ import absolute_import in your xyz.py file.
Check your current directory. It must be main_directory.
import os
print("Current working directory is: ", os.getcwd()
if not, you can change using
os.chdir("path/to/main_directory")
also works with relative path
os.chdir('..')
I was also facing same problem when you use row python script so i use the following code at the beginning of the file
import os
import sys
current_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
This way it will search the require file at parent directory.
Hope this will work for you also..
You could move your utils folder into drivers, making the path to the to-be imported file a subdirectory of your executing file, like:
main_directory/drivers/utils/connect.py
Alternatively, you could try
from ..utils import connect as dc
This will move up a directory before import.
Lasty, you could add the directory to Path in your script via
import sys
sys.path.insert(0,'/path/to/mod_directory')
For this method, see also this question
Here is the structure of my directory:
MyFolder
-run.py
SecondFolder
-class.py
What I have attempted is adding the directory path to sys.path within the run.py file and this will work only occasionally (not sure why):
import sys
sys.path.insert(0, '/Users/.../SecondFolder/class.py')
from class import Connection
How can I ensure the module is always loaded? Any help is greatly appreciated.
If SecondFolder doesn't have to be in the same location as MyFolder, you can add it to the python site-packages.
From there, you can import it as so:
from SecondFolder.class import Connection
I have a number of Python files in a parent folder called 'API' and I'm trying to link them together:
API/auth/module1.py
API/subfolder/prgm.py
From the parent to the child folders, I have an init.py file containing paths or program names to call, however when I go to execute '/subfolder/prgm.py' that has a call to import 'module1.py', I get the following error at execution:
machine01% ./prgm.py
Traceback (most recent call last):
File "./prgm.py", line 2, in <module>
from API.auth.module1 import authFunction
ModuleNotFoundError: No module named 'API'
This is the import statement I have in 'prgm.py':
from API.auth import module1
This question is a bit different from previous ones because I am trying to get a python script that is already in one sub-folder to access a module in another subfolder but under the same parent 'API' folder. Previous questions involved the python script being based in the parent folder and calling modules located in sub-folders.
If you really need to run API/subfolder/prgm.py which in turn import API/auth/module1.py
In prgm.py you could add a parent directory (which is 'API') to sys.path like this:
import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
And now you could import anything from inside of 'API':
from auth import module1
try """from . auth import module1""" may be?
I have multiple modules in my project and specify some execution point. But when I try to import files from submodules, it doesn't work.
So, how to specify submodules to execute from selected execution file?
project
--bin
---- executeFile
--modules
---- __init__.py
----fileA.py
in executeFile, I try:
from ..modules.fileA import *
but get the error:
Traceback (most recent call last):
File "./bin/muexecute", line 10, in <module>
from ..modules.os import *
SystemError: Parent module '' not loaded, cannot perform relative import
I found solution.
The problem was in my opinion about using init.py.
I placed in executable scripts path to including and it works fine
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)))
So you are having trouble defining your relative path, correct? Try the following:
from sys import path
path.append('C:\\realative_path')
from function_file import required_function
Hope that helps.
All modules you want to import should in in your PYTHONPATH. Therefore there is no hierarchy.
In your case It seems to me that an __init__.py is missing from your project's main folder (with all the models included), so executefile doesn't know about your modules.
I've read through a couple of similar questions, notably this one about imp.load_module which seems to be close to what I want, but I can't understand why I'm still getting ImportErrors. Here is my folder hierarchy:
program\
__init__.py
main.py
thirdparty\
__init__.py
css\
__init__.py
css.py
utils\
__init__.py
http.py
In main.py I have the following code. This is intended to search the thirdparty\ directory and load each module it finds. Each module is in its own separate directory.
import os
import imp
for root, dirs, files in os.walk("thirdparty"):
for source in (s for s in files if s.endswith(".py")):
name = os.path.splitext(os.path.basename(source))[0]
m = imp.load_module(name, *imp.find_module(name, [root]))
The problem is that css.py happens to use its own subfolder that it loads stuff off of, utils. It has a line in it that says:
from utils import http
And that is where it fails. I get this error when I run main.py.
Traceback (most recent call last):
File "main.py", line 7, in <module>
m = imp.load_module(name, *imp.find_module(name, [root]))
File "thirdparty/css/css.py", line 1, in <module>
from utils import http
ImportError: No module named utils
I'm stumped. css.py is self contained in its own folder, and when I run css.py separately it imports utils just fine. What is causing this?
Maybe you can solve this by changing the import to:
from .utils import http
Or by adding the folder you import to the Python Path:
sys.path.append(os.path.join(root, source))
When you import modules in thirdparty, the place Python looks for modules is still the main directory. The initial import works, because you give the right path to imp.find_module, but after that Python has no idea where to look for the modules.