简体   繁体   中英

Import module from child folder instead of same directory?

So I have the following file structure (win10)

project/
        mycode.py
        lib/
           bunch of python modules
           paramiko/
                    all of paramiko's files

Here, all the modules are in a child folder, and when I say import paramiko in mycode.py, it can't find paramiko. However, when I move them all out of the lib directory, it works fine.

Working solution:

project/
        mycode.py
        bunch of python modules
        paramiko/
                 all of paramiko's files

But it's ugly, and I'd rather have all of them in a lib directory. How do I access modules in a child directory?

Edit: Okay, figured it out. I used os. to add to the path:

projectPath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(projectPath+"\\lib")

which I had tried before, except this time, i moved the import paramiko to after the edits made to the path . God I feel stupid sometimes

You can also do this without adding it to the path:

from lib import paramiko

OR

import lib.paramiko

As long as you have the directory structure like this

project/
        mycode.py
        lib/
           bunch of python modules
           paramiko/
                    all of paramiko's files

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