Import file from subdirectory into file in another subdirectory - python

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

Related

Import Error Attempted relative import when importing from another folder

It might be a pretty simple error but I don't get to solve it. The issue is that I have two folders, folder1 and utils. Inside folder one, I am trying to import a function from utils.py script in utils folder. Both folders have their respective init files. However, I get this import error and I don't know why.
Folder1
Script1.py
utils
utils.py
The way I try to import the package is:
from .utils.utils import *
Is there anything I am doing wrong?
I had written a utility script which I wanted to use for rest of my scripts. This is how I import -
sys.path.append(path_to_script)
import my_util as mu
df = mu.get_data()
We need to add the path to sys.path and then we can access that as a module.
path_to_script is the absolute path of the directory where your script/files are.
If the script is in same directory then we can simply import it as -
import my_util as mu
df = mu.get_data()
In this case, we do not need to add the path to sys.path as well. It is simply like importing another file inside a python application.

Python Import custom library from another directory

I have the following folder format
Main Folder
-DataManagement
-Libraries
-TransformLibrary
__init__.py
transform.py
-DataUsage
-TransformData
main.py
I wish to call Transform.py from main.py. However I need this to be relative, meaning that if somebody clones my project, it can run without changing any paths.
Thanks!
You could use sys.path to both find your current directory, and include your module in sys.path so that Python can find it. However, this solution is a bit messy:
import sys
import os
# Get current directory
current_dir = sys.path[0]
# Create path to 'Main Folder/DataManagement/Libraries'
search_dir = os.path.join(current_dir.split('DataUsage')[0], 'Libraries')
# Make Python search for new path
sys.path.append(search_dir)
from TransformLibrary import transform # transform.py is imported

Import from another directory

I need to import .py file from another one in another directory (import app2 from app1)
So there is directory tree
app:
dir1:
app1.py
dir2:
app2.py
My problem is almost like Importing from another directory, but this solution doesnt work for me for some reason
Furthermore i've been trying to do like this (app1.py)
from ..dir2 import app2
The error is:
Attempted relative import beyond top-level package
How can i solve this?
Add your additional directories to the system path
import sys
sys.path.insert(0, "/path/to/app1/dir2")
sys.path.insert(0, "/path/to/app2/dir2")

Import class from Python file in another folder -- not a child folder

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

Cannot find module when importing from project in python

My directory structure looks like this:
I have some utility functions in util/misc.py that I want to import in compose_dataset.py. However, I cannot get the import statement to work.
I'm working on Windows Python3.5.4, so from what I've read I don't need __init__.py files anymore. The project folder is a child of my PYTHONPATH that points solely to E:\Python. So far, I tried:
from misc import *
from util import *
from util.misc import *
from ..util.misc import *
and either received ImportError: No module named 'xyz' or ImportError: attempted relative import with no known parent package. I also tried adding init-files but I have no experience with those and simply added one to every directory, but (surprisingly) that didn't work either.
What am I missing here??
Try this:
import sys
sys.path.insert(0, '../')
from util.misc import *
You may also want to take a look at this post: How to access a module from outside your file folder in Python?
Set your PYTHONPATH to ., and add __init__.py files into each directory, where you want to import from, in your case add it into src, data, util directories. Assuming that you run your "entry point" script from the root directory of your project (same where your README.md file is), to import use this code:
# compose_dataset.py file
from src.util.misc import function_name

Categories

Resources