Importing a python file another directory - python-3.x

I am trying to import test.py from within main.py how would I be able to do that? Both main.py and test.py is allocated within the application folder. The test.py file is within the app folder.
Directories
application folder
├── appFolder
│ └──test.py
└── main.py
Code within Main.py
from .TimeandClose import test```

Use the following code:
from appFolder import test

Related

Unable to import flask app folder in unittest folder of an repo

I am facing issues in writing unit test for my flask app. Exact issue is that test files in unit-test directory is not able to import files from app folder.
My directory structure:
.
├── Dockerfile
├── README.md
├── app
│ ├── __init__.py
│ ├── api.py
│ └── wsgi.py
├── docker
│ ├── docker-compose.yml
│ └── start.sh
├── requirements.txt
└── unit-test
├── __init__.py
└── test_api.py
Code in unit-test/test_api.py:
import unittest
from app import api
Absolute import throws this error:
from app import api
ModuleNotFoundError: No module named 'app'
I have tried the following after checking a few resources of absolute and relative imports, none of them worked.
from .. import app
error:
from .. import app
ImportError: attempted relative import with no known parent package
I checked a few questions on SO and someone recommended having _init_.py file in the unit-test folder as well but I already have a blank init.py file there.
I have reviewed numerous blogs and youtube tutorials and absolute imports work for them easily.
Please advise how to fix this error and run unit tests.
import sys
sys.path.append('/path/to/the/required/folder')
import name_of_file
if not an inbuilt package, Python only searches in the current directory when you try to import, thus we have to add this path, so that it looks inside this particular folder as well. After adding that, you can simply do the import.

Running a python file within a different directory

How could I run the entirety of test.py from main.py. Both main.py and test.py is allocated within the application folder. The test.py file is within the app folder. How would I be able to achieve this, the code I have below does not work?
Directories:
application folder
├── appFolder
│ └──test.py
└── main.py
Main.py:
from .appFolder import test
from subprocess import call
call(["Python3","test.py"])
You don't need to import anything, just reference the folder name in main.py. To make it more robust, you should probably use a relative file otherwise you might get some odd results depending on where main.py is called from.
import os.path
from subprocess import call
d = os.path.dirname(os.path.realpath(__file__)) # application folder
call(["python3", f"{d}/appFolder/test.py"])
See also: https://stackoverflow.com/a/9271479/1904146

Python cannot import py files in the same folder

VSCode Version: 1.41.1
OS Version:Ubuntu 18.04
Steps to Reproduce:
# tree:
.
├── demo1
│ ├── __init__.py
│ └── test.py
├── __init__.py
├── auto.py
# auto.py
def func():
print("1")
# test.py
from auto import func
func()
Use examples to solve problems that arise in a project
Run the test.py file, and I get "ModuleNotFoundError: No module named 'func'"
I used 'CTRL '+ left mouse button in test.py to jump to func
The same code can be run in pycharm
If you run test.py directly then you need to add the parent folder to PYTHONPATH. Try:
import sys
sys.path.append("..\<parent_folder>")
from auto import func
Otherwise, if you merely want to import test.py in another .py file, you can use relative import of python
from . import auto #another dot '.' to go up two packages
auto.func()
Reference
Add this in test.py, before import:
import sys
sys.path.insert(0, "/path/to/project/root/directory")
For me it's not a good file organization. A better practice might be as below:
Let your project file tree be like:
.
├── __init__.py
├── lib
│ ├── auto.py
│ └── __init__.py
└── test.py
And write test.py like:
from lib.auto import func
func()
Simple one-line solution
from ... import auto
and call the function by using auto.func().

How to import module so that it can be accessed from any directory?

I have the following project structure:
x/
a.py
b.py
main.py
a.py:
from b import *
class A:
.....
main.py
from x.a import A
.....
I want to be able to run a.py independently as well as access its functionality through main.py
I'm able to run a.py but when I try to import it as shown in main.py, the module is unable to be found. I can fix this problem by adding the following line to a.py:
sys.path.append(os.path.join(os.path.dirname(__file__)))
but this feels hacky. Is there a better way to achieve the desired behavior?
You need to mark the directory "x" as a package to be able to load anything off it.
As stated in the official documentation of Python, you have to create an empty "__init__.py" file in the root of "x" to mark it off as a package.
Then your directory structure should look something like this:
.
└── x
├── __init__.py
├── a.py
└── b.py
└── main.py
You may want to edit "a.py" to load the modules relative to the package it is in using a period to represent the current package:
# x/a.py
from .b import *
class A:
# rest of your code

why does import module in same directory gets error

directory structure
test/
__init__.py
line.py
test.py
test.py
from . import line
output:
Traceback (most recent call last):
File "test.py", line 1, in <module>
from . import line
ImportError: cannot import name 'line'
I know I can just import line. but it may import standard library in python3.
why did this error happen? does python3 support this syntax?
ps: I'm not in interactive console and test directory has already been a package
I'm not sure if you can import module with the same name as library utilities directly. However, you could consider putting your modules inside a package, so your directory structure would look like:
.
├── main.py
├── package
│   ├── __init__.py
│   ├── line.py
│   ├── test.py
Where __init__.py might have some setup commands (you can omit this file if you have none) and in main.py you can do the following:
from package import line
...
Within the directory package if you'd like to say, import line.py in test.py you can use the syntax:
from . import line
Note relative imports (using the from . notation) will only work inside the script and not in the interactive console. Running the test.py ( if it's using relative imports) directly will also not work, although importing it from main.py will work.

Resources