简体   繁体   中英

Importing file from a different directory in another file

I am new to python and have been trying to import a function that lies in a different file.

My file tree is like below

MainDir 
  ->folder1
     ->file1.py
 ->CommonFunctions.py

CommonFunctions.py lies in the main directory and I want to use the functions of CommonFunctions.py in file1.py

My CommonFunction.py has below code

class CommonFunctions(unittest.TestCase):
    def setUp(self):
            logging.info('CALLED')

I want to use the setUp function from file1.py

I have tried imports but thats not working, any help really appreciated. FYI, am using Python 2.7

Use two dots to specify one directory up (one dot would mean current directory instead of python path):

from ..CommonFunctions import random_func

From PEP 328 :

One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod.

Remember that you can always append to system path like so:

import sys
sys.path.insert(0, '/path/to/file')

import file

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