简体   繁体   中英

Import class from Python file in another folder — not a child folder

Here is the structure of my directory:

MyFolder
   -run.py
SecondFolder
   -class.py

What I have attempted is adding the directory path to sys.path within the run.py file and this will work only occasionally (not sure why):

import sys
sys.path.insert(0, '/Users/.../SecondFolder/class.py')
from class import Connection

How can I ensure the module is always loaded? Any help is greatly appreciated.

If SecondFolder doesn't have to be in the same location as MyFolder, you can add it to the python site-packages.

From there, you can import it as so:

from SecondFolder.class import Connection

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