I'm very new to python and I have a directory structure like this:
root
--child
-----config.py
example.py
In example.py I just tried:
import child
but that doesn't seems to be working.
Where I'm making the mistake!
Do you have a __init__.py file in root/child/ directory? After creating this file you should be able to do this:
import child.config
or
from child import config
You can also import multiple modules from child directory like this:
from child import first, second, third
Read about modules and packages here.
If you want to import config.py with importing child you need to define child as a package.
To do so you need to create an __init__.py file in your child directory.
Check this about packages
Your directory should have init.py so that python will understand it is a package. So the directory structure would be like
root
__init__.py
child
__init__.py
config.py
example.py
import root.child
note, you should import root.child not child.
Create an empty __init__.py file in same directory with config.py. This is required for importing files like a package.
Then you can import it.
Related
I've been looking around this site for how I can import a class stored in a folder at the same hierarchy level. What I found is that using .. should bring me up one folder. Or at least, that is how I read it as that assumption seems to be wrong.
src/
folderStrucutre1/
__init__.py
fileToImport.py <- contains A
folderStrucutre2/
someFile.py
__init__.py
abc.py
Having above folder structure in which fileToImport.py contains a class named A. How would I import A into someFile.py?
Due to how packages work in python, you need to move src and abc.py into a subfolder, and provide an __init__.py for it.
The directory structure should look like this after the changes:
package-name/
package-name/
folderStructure1/
__init__.py
fileToImport.py <- contains A
folderStructure2/
__init__.py
someFile.py
__init__.py
abc.py
Then, in someFile.py you can import A using a relative import from the parent package:
from ..folderStructure1.fileToImport import A
Lastly, you should open the topmost folder (parent to abc.py) for IDE intellisense to work
First, we need to create the absolute path to your src folder without hard-coding it in your script to make it portable.
Add this code in your someFile.py file.
import os
src_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Now, let's add your folderStructure1 directory to the Python Search Path
import sys
sys.path.append(src_path + '/folderStructure1')
Now you can use the following:
from fileToImport import Class
object = Class()
You can add src to the python search path and then you can import A from fileToImport.py.
For this, you should write someFile.py like:
import sys
sys.path.append("..") # .. represente the father folder
from folderStrucutre1.fileToImport import A
instance_for_A = A()
How do I link the util.py file to the script.py file?
App
Module
__init__.py
util.py
Main
__init__.py
Dir1
script.py
__init__.py
Dir2
script.py
__init__.py
Take this directory layout of my app. It's a bit more complex for requirement reasons to keep the scripts easily separated while sharing the same module across each script. However, it's difficult to find the correct way to import that module to each script due to directory hierarchy.
Environment
Python 2.7, Windows 10, 64Bit
Just add the root directory to the PYTHONPATH. Then you can use absolute imports as well as the relative ones.
# script.py
form Module.util import _
You can put:
import sys
sys.path.insert(1, '.')
in your Module.__init__.py and then just import it in script.py with:
from Modules import util
Additionally you can define a __all__ = [] variable in your __init__ and then you can star import.
The project structure on my local machine is setup like this:
python/
__init__.py
readText.py
testing/
__init__.py
removeDuplicates.py
In removeDuplicates.py I am trying to import as follows:
from python import readText
This gives: ImportError: No module name 'python'
My init.py in both folders are blank by the way.
You need the parent directory of your python subdirectory to be present in sys.path. If you execute your script from that directory, the import should work. But the easiest way to do this is to export the environment variable PYTHONPATH.
You want to import something from the parent directory, use
from .. import readText
see relative imports:
https://docs.python.org/2.5/whatsnew/pep-328.html
Simple question, but could not find the answer.
I've following structure:
./lib1:
main.py
./lib2:
__init__.py utils.py
From the root diretory, I'm running:
python lib1/main.py
and in main.py I want to import lib2/utils.py.
adding import lib2/utils.py fails.
One solution I found is to add:
~/tmp/root$ cat lib1/main.py
import sys,os
sys.path.append(os.getcwd())
import lib2.utils
lib2.utils.foo()
which is good, but I wander if there is other solution. Thanks.
Are lib1 and lib2 separate modules? If yes, the comment by #BrenBarn applies: You need to add the top directory (containing lib1 and lib2 to the Python path (e.g using PYTHONPATH environment variable or appending to sys.path).
If both lib1 and lib2 are part of one module (i.e. there is a __init__.py file in the top directory) you can use relative imports (https://docs.python.org/2.5/whatsnew/pep-328.html).
Your problem is caused by using the wrong directory structure. The main.py script should be in the same top-level directory as the package that it needs to import. So the structure should look like this:
project /
lib2 /
__init__.py
utils.py
other.py
main.py
The directory of the main script will always be added to the start of sys.path, so this will guarantee that any packages in that directory can be always be directly imported, no matter where the script is executed from.
To import the utils module into main.py (or other.py), you should do:
from lib2 import utils
I have the following directory structure:
application
tests
main.py
main.py
application/main.py contains some functions.
tests/main.py will contain my tests for these functions but I can't import the top level main.py. I get the following error:
ImportError: Import by filename is not supported.
I am attempting to import using the following syntax:
import main
What am I doing wrong?
If you'd like your script to be more portable, consider finding the parent directory automatically:
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# import ../db.py
import db
You must add the application dir to your path:
import sys
sys.path.append("/path/to/dir")
from app import object
Or from shell:
setenv PATH $PATH:"path/to/dir"
In case you use windows:
Adding variable to path in windows.
Or from the command line:
set PATH=%PATH%;C:\path\to\dir
Please mind the diff between PYTHONPATH, PATH, sys.path.
Late to the party - most other answers here are not correct unfortunately - apart LennartRegebro's (and BrenBarn's) which is incomplete. For the benefit of future readers - the OP should, first of all, add the __init__.py files as in
root
application
__init__.py
main.py
tests
__init__.py
main.py
then:
$ cd root
$ python -m application.tests.main
or
$ cd application
$ python -m tests.main
Running a script directly from inside its package is an antipattern - the correct way is running with the -m switch from the parent directory of the root package - this way all packages are detected and relative/absolute imports work as expected.
First of all you need to make your directories into packages, by adding __init__.py files:
application
tests
__init__.py
main.py
__init__.py
main.py
Then you should make sure that the directory above application is on sys.path. There are many ways to do that, like making the application infto a package and installing it, or just executing things in the right folder etc.
Then your imports will work.
You cannot import things from parent/sibling directories as such. You can only import things from directories on the system path, or the current directory, or subdirectories within a package. Since you have no __init__.py files, your files do not form a package, and you can only import them by placing them on the system path.
To import a file in a different subdirectory of the parent directory, try something like this:
sys.path.append(os.path.abspath('../other_sub_dir'))
import filename_without_py_extension
Edit: Missing closing bracket.
in python . exists for same directory, .. for parent directory
to import a file from parent directory you can use ..
from .. import filename (without .py extension)