简体   繁体   中英

Importing from folders at the same hierarchy level

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM