This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Python package structure
Hello,
I'm looking to import a python file that I have in a sub-directory that is below the root of my main file. e.g.
import ../library/utils.py
When I put that into my code and run it I get a compile error.
Is there a way to include files from below the main file root directory or does it have to be in a sub-directory in the root?
Thanks for your help.
You don't import files, you import modules. Modify sys.path accordingly, and do import utils, e.g.
import sys
sys.path.append('../library')
import utils
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'library')))
import utils
This will modify the sys.path variable that contains the directories to search for files. It will also make sure that it will find it properly even if you run it as:
$ python the_file.py
$ python ../the_file.py
$ python /somewhere/over/the_file.py
This will work for stuff under development, testing, training. Installed files will not need such a construct.
Related
This question already has answers here:
Importing files from different folder
(38 answers)
How to fix "Attempted relative import in non-package" even with __init__.py
(22 answers)
Closed 2 months ago.
This is my project structure:
/my_project
/first_folder
first.py
/second_folder
second.py
second.py
def hello():
print('hello')
first.py
from ..second_folder import second
second.hello()
when i run first.py i get the following error:
ImportError: attempted relative import with no known parent package
How can I avoid this problem?
Normally when you run your script as the main module, you shouldn't use relative imports in it. That's because how Python resolves relative imports (using __package__ variable and so on...)
This is also documented here:
Note that relative imports are based on the name of the current
module. Since the name of the main module is always "__main__",
modules intended for use as the main module of a Python application
must always use absolute imports.
There are ways to make this work for example by hacking __package__, using -m flag, add some path to sys.path(where Python looks for modules) but the simplest and general solution is to always use absolute imports in your main script.
When you run a script, Python automatically adds the directory of your script to the sys.path, which means anything inside that directory (here first_folder is recognizable by interpreter. But your second_folder is not in that directory, you need to add the path to the my_project(which has the second_folder directory) for that.
Change your first.py to:
import sys
sys.path.insert(0, "PATH TO /my_project")
from second_folder import second
second.hello()
This way you can easily go into first_folder directory and run your script like: python first.py.
Final words: With absolute imports, you don't have much complexity. Only think about "where you are" and "which paths are exists in the sys.path".
There are several sources for this error but, probably, if your project directory is my_project then you don't need .. in the import statement.
from second_folder import second
This question already has answers here:
Import Script from a Parent Directory
(3 answers)
Closed 1 year ago.
File Organization
./helper.py
./caller1.py
./sub_folder/caller2.py
It's fine when importing helper.py from caller1.py.
caller1.py
from helper import hello
if __name__ == '__main__':
hello()
but when importing from ./sub_folder/caller2.py with the exact same code I got the error...
ModuleNotFoundError: No module named 'helper'
I would like to organize files into sub-folders because the project is quite large.
As a solution for this,
You can add the path of that file in system using sys module and then you can import that perticular file.
like in your case
caller2.py
import sys
sys.path.insert(0, "C:/Users/D_Gamer/Desktop/pyProject/helperDir")
# You need to provide path to the directory in which you have a helper file so basically I have "helper.py" file in "helperDir" Folder
from helper import hello
if __name__ == '__main__':
hello()
There are other ways to achieve the same but for now you can hold onto this and
for more information checkout this reference on Github
You have to understand how Python finds the modules and packages when using import.
When you execute a python code, the folder in which this file is will be added to the PYTHONPATH which is the list of all the places where python will look for your packages and modules.
When you call caller1.py, it works because helper.py is in the same folder but it does not work for caller2.py because python does not find it in the same folder nor the other path in PYTHONPATH.
You have three options:
call caller2.py from a script in the same folder as helper
add the folder containing helper.py in the PYTHONPATH (not recommended)
make your code into a package that you can pip install -e, this way python will be able to find your modules as they will be install in the site-packages of your python environment (most complex but cleanest solution)
This question already has answers here:
Relative imports in Python 3
(31 answers)
Closed 4 months ago.
from ..box_utils import decode, nms
This line is giving error
ImportError: attempted relative import with no known parent package
What is this error and how to resolve this error?
Apparently, box_utils.py isn't part of a package. You still can import functions defined in this file, but only if the python script that tries to import these functions lives in the same directory as box_utils.py, see this answer.
Nota bene: In my case, I stumbled upon this error with an import statement with one period, like this:
from .foo import foo. This syntax, however, tells Python that foo.py is part of a package, which wasn't the case. The error disappeared when I removed the period.
If a different dictionary contains script.py, it can be accessed from the root. For instance:
If your program is structured...:
/alpha
/beta
/delta
/gamma
/epsilon
script.py
/zeta
...then a script in the epsilon directory can be called by:
from alpha.gamma.epsilon import script
in the latest python version, import it, directly don't use .. and .library
import the file which you want. this technique will work in the child directory.
If you import it from parent directory, then place the directory's full path.
package
|--__init__.py
|--foo.py
|--bar.py
Content of bar.py
from .foo import func
...
If someone is getting the exactly same error for from .foo import func.
It's because you've forgot to make it a package. So you just need to create __init__.py inside package directory.
This question already has answers here:
How do I import other Python files?
(23 answers)
Closed 5 years ago.
Can I import the test01.py like os, sys module?
I want to import the test01.py like:
import test01.py
In this case now, I only can import it like this:
from testDemo02 import test01
Is it possible to reach it?
It looks like test01 is in the package testDemo02 - you can tell because there is a file __init__.py in the directory testDemo02. Given that, there are a couple possibilities:
If the parent directory of testDemo02 is in the module search path (sys.path), but testDemo02 itself is not, you can import your test01 module using either
import testDemo02.test01
or
from testDemo02 import test01
I suspect this is the case since you tried the latter one and it works. This is what I would expect because I see that __init__.py file there.
If testDemo02 itself is in the search path, you will be able to import your module with just
import test01
I would find it strange for a directory to be in the search path when it also contains an __init__.py file, but it is possible.
You can use sys module's path property to append your path:
>>> import sys
>>> sys.path.append("/testDemo02/test01")
>>> import test01
This question already has answers here:
Import python package from local directory into interpreter
(10 answers)
Closed 9 years ago.
I'm writing an installation program that will pull a script out of an existing Python file and then use it in the main Python program. What I need to know how to do is import <file> from the current working directory, not the standard library or the directory the main code is in. How can I do that?
This works:
import os
import sys
sys.path.append(os.getcwd())
import foo
import sys
sys.path.append('path/to/your/file')
import your.lib
This will import the contents of your file from the newly appended directory. Appending new directories to the Python Path in this way only lasts while the script is running, it is not permanent.
You should be able to import the module from your current working directory straight away. If not, you can add your current working directory to sys.path:
import sys
sys.path.insert(0, 'path_to_your_module') # or: sys.path.insert(0, os.getcwd())
import your_module
You can also add the directory to PYTHONPATH environment variable.