this is my file system:
source:
|_ folder1:
myfile.py
|_ folder2:
infile.py
I am currently working with "infile.py" and I want to import myfile.py from folder1, doing the following:
from ..folder1.myfile import *
result:
ImportError: attempted relative import with no known parent package
in my file I don't have any class, only functions, so I don't know if it is necessary to create a class in order to import a file as a module in Python.
I'm getting a ModuleNotFoundError while running my flask app with this dir structure:
project
| app
| __init__.py
| urls.py
| views.py
| __main__.py
In the project dir, while running python3 ., I'm getting a
File "./app/__init__.py", line 4, in <module>
import urls
ModuleNotFoundError: No module named 'urls'
The content of __init__.py is
#!/usr/bin/env python3
import logging
import flask_cors
import urls
from views import flask_app
log = logging.getLogger("werkzeug")
log.disabled = True
flask_cors.CORS(flask_app)
def run(host, port):
flask_app.run(host=host, port=port)
The code is a little big so this is the link to it.
If you want to import other files in the same directory in a __init__.py file, you need to use relative import syntax:
from . import urls
This way Python will look for urls.py alongside your __init__.py, instead of searching in sys.path.
> Project
>> __init__.py
>> moduleA
>>> __init__.py
>>> file_1.py
>> moduleB
>>> __init__.py
>>> file_2.py
I have the following Directory Structure for a Python Project. I want to import file_1.py into file_2.py . How can I do so ?
I tried inserting the given below snippet in file_2.py:
from ..moduleA import file_2
But I keep Getting this error:
ImportError: attempted relative import with no known parent package
I also tried this
from Project.moduleA import file_1
This method works in the PyCharmIDE but won't work in VSCode wherein I get this error
ModuleNotFoundError: No module named 'Project'
I am new to Python. This really confused me!
My directory structure is like this:
Project
| - subpackage1
|- a.py
| - subpackage2
|- b.py
| - c.py
When I import a.py into b.py with from subpackage1 import a, I get a ModuleNotFoundError. It seems like I cannot import a file from the parent directory.
Some solutions suggest to add an empty file __init__.py in each directory, but that does not work. As a work around, I have put the following in each subfile (i.e., a.py and b.py) to access the parent directory:
import os
import sys
sys.path.append(os.path.abspath('..'))
I have tried to output sys.path in subfiles, it only includes the current file path and anaconda path, so I have to append .. to sys.path.
How can I solve this problem? Is there a more efficient way?
Suppose we have this files and directories tree:
$> tree
.
├── main.py
├── submodule1
│ ├── a.py
│ └── __init__.py
└── submodule2
├── b.py
└── __init__.py
2 directories, 5 files
So, here is an example of how to do the import from a.py inti b.py and vice-versa.
a.py
try:
# Works when we're at the top lovel and we call main.py
from submodule1 import b
except ImportError:
# If we're not in the top level
# And we're trying to call the file directly
import sys
# add the submodules to $PATH
# sys.path[0] is the current file's path
sys.path.append(sys.path[0] + '/..')
from submodule2 import b
def hello_from_a():
print('hello from a')
if __name__ == '__main__':
hello_from_a()
b.hello_from_b()
b.py
try:
from submodule1 import a
except ImportError:
import sys
sys.path.append(sys.path[0] + '/..')
from submodule1 import a
def hello_from_b():
print("hello from b")
if __name__ == '__main__':
hello_from_b()
a.hello_from_a()
And, main.py:
from submodule1 import a
from submodule2 import b
def main():
print('hello from main')
a.hello_from_a()
b.hello_from_b()
if __name__ == '__main__':
main()
Demo:
When we're in the top level and we're trying to call main.py
$> pwd
/home/user/modules
$> python3 main.py
hello from main
hello from a
hello from b
When w're in /modules/submodule1 level and we're trying to call a.py
$> pwd
/home/user/modules/submodule1
$> python3 a.py
hello from a
hello from b
When we're /modules/submodule2 level and we're trying to call b.py
$> pwd
/home/user/modules/submodule2
$> python3 b.py
hello from b
hello from a
The first issue you're getting is due to that from subpackage1 import a line in your b.py module.
b.py is located in your subpackage2 package, a sibling package of subpackage1. So trying to run from subpackage1 import a means the subpackage1 is within subpackage2 which is incorrect. Also as side note, in python3 you should never use implicit relative imports as it no longer supports it, so instead use explicit relative imports.
Adding an __init__.py in each folder turns them in python packages, and you can keep them empty. You want to replace the from subpackage1 import a with either an explicit relative import like from ..subpackage1 import a or an absolute import like from Project.subpackage1 import a. This will be the efficient and correct way to write your package, and you can test it by writing a script that imports Project and uses its subpackages and modules.
However, I am assuming you are running b.py as a main module to test the imports. This means you are running command lines that look like: python b.py. Running it like this gives you a module search path that does not have any of the parent paths like Project. This would lead to you keep getting ModuleNotFoundErrors even though there's nothing technically wrong with your package. This is why you need a sys.path.append(... work-around that manually appends your parent path to the module search path in order to run your b.py module as a main module. If this helps you to test your code then by all means use it, but it is fine to use the absolute and explicit relative imports because modules in a package are supposed to work that way.
Firstly, you need create file __init__.py in subpackage1 to declare it is a module
touch subpackage1/__init__.py
Secondly, you can try relative import in python3
# b.py
from ..subpackage1 import a
Or you can add your current directory to $PYTHONPATH
export PYTHONPATH=${PYTHONPATH}:${PWD}
One way to access the subpackage is using . operator going all the way up to top package or file directory. Thus if the structure is
top_directory
|- package1
|- subpackage1
|- a.py
|- package2
|- subpackage2
|- b.py
Then you use the following
#b.py
from top_directory.package1.subpackage1 import a
statements...
The from statement must go all the way up to the top directory covering both a.py and b.py.
This SO Q&A discusses options for adding your project root to the PYTHONPATH.
1. mac/linux:
add export PYTHONPATH="${PYTHONPATH}:/path/to/Project_top_directory" to your ~/.bashrc
2. path config file:
Alternatively, you can create a path configuration file
# find directory
SITEDIR=$(python -m site --user-site)
# create if it doesn't exist
mkdir -p "$SITEDIR"
# create new .pth file with our path
echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth"
How can I import module at parent directory?
In following package, I want to use techniques module in main.py
I am using __all__ to ignore tests when import trade.
trade/
__init__.py
htmlparser.py
utils.py
techniques.py
tests/
testdata.json
main.py
__init__.py:
__all__ = ["techniques", "utils", "htmlparser"]