简体   繁体   中英

Importing a module from elsewhere in directory

I have seen many attempts at answering this, but none have successfully aided in all instances for me. My directory looks like the following:

folder1
   -file1.py
   -folder2
      -file2.py

I have attempted the following from many SO answers, in file2.py :

import sys
sys.path.insert(1, '.../folder1/file1.py')
from file1 import funx

This worked when file2 was above file1 in the hierarchy or if they are in the same folder, but with the above hierarchy I get a ModuleNotFoundError .

Any help in resolving this would be very useful? I am mostly interested to see if there is a way to have the module be in a place where it can be called just like other python modules ( sklearn , pandas , etc.) regardless of location in my directory. Thanks!

If you want to create a module for global access-- In console--

$python

$python
>>> import sys
>>> print(sys.path) 

The output may look like -

C:\\\\Python27\\\\lib\\\\site-packages -- in Windows

or

/usr/bin/python2.7/site-packages -- in mac

Copy the file you want to have global access to this location.

In your program you can import file directly like---

from file1 import funx

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